6

我正在做一个 react-native 项目,在那里我很难理解 props 在功能组件之间的工作方式。我的要求是创建一个可重用的按钮组件,我可以在我的项目内的资源文件中传递图像位置,因此它会为我创建按钮。出于某种原因,如果我手动提供所需的位置,它将起作用并为我创建按钮,但如果我\我将该位置作为我创建的道具传递,则由于某种原因它将不起作用。我的代码如下。

按钮组件

import React, { Component } from 'react';
import {
    View,
    StyleSheet,
    Image,
    TouchableOpacity
} from 'react-native';

const ButtonWithImage = (props) => {
    const {buttonStyle} = styles;
    const clickEvent = () => {}

    return (
        <TouchableOpacity onPress= {clickEvent}style={buttonStyle}>
            <Image 
                source={props.imagePath} 
                style={styles.ImageIconStyle} 
            />
        </TouchableOpacity>
    );
};

const styles = {
    buttonStyle: {
        //alignSelf:'stretch',
        height: 50,
        width:50,
        paddingTop:0,
        flexDirection: 'row'
    }
};

export default ButtonWithImage;

我创建按钮并传递道具的地方

import React, { Component } from 'react';
import {
    View,
    StyleSheet,
    Dimensions,
} from 'react-native';
import FooterIcons from './ButtonWithImage'

const Footer = () => {
    return (
        <View style={styles.footerStyle}>
            <FooterIcons imagePath = {'./images/homeButton/homeBtn.png'} />
        </View>
    );
};

const styles = StyleSheet.create({
    footerStyle: {
        height: 60,
        width: 100,
        // justifyContent:'flex-start'
    },
});

export default Footer;
4

2 回答 2

18

这是不可能的,因为您想要一个具有本地路径的图像, <Image source={require(props.path)} />而这不起作用,因为require只能将字符串文字作为参数。

这意味着您必须执行以下操作:

<FooterIcons imagePath = {require('./images/homeButton/homeBtn.png')} 
/>

让它发挥作用。并且不要忘记给你的图像一个widthheight

或者

您可以采用一种适用于没有大量图像的应用程序的方式来执行此操作,因为我们将预加载它们:

1- 制作一个资产 javascript 文件 assets.js ,这个文件应该需要你所有的本地图片,像这样:

const assetsObject = {
  homeIcon: require('./images/homeButton/homeBtn.png')
  boatIcon: require('./images/homeButton/boat.png')
  ....
  ...
}
module.exports = assetsObject

2-现在您需要在 ButtonWithImage.js 文件中使用此文件

const assets = require('./assets.js')

const ButtonWithImage = (props) => {
  const {buttonStyle} = styles;
  const clickEvent = () => {}

  return (
      <TouchableOpacity onPress= {clickEvent}style={buttonStyle}>
         <Image 
            source={assets[props.imagePath]} 
            style={styles.ImageIconStyle} 
         />
      </TouchableOpacity>
  );
};

3-您发送给 ButtonWithImage 的道具应该在我们创建的 assetsObject'homeIcon''boatIcon'..etc的键上

const Footer = () => {
return (
    <View style={styles.footerStyle}>
        <FooterIcons imagePath = {'homeIcon'} />
    </View>
);
};

4-不要忘记给你的图像一个宽度高度

就是这样,我建议不要再调用道具 imagePath,也许只是图像。

于 2018-01-22T16:58:40.870 回答
0

您可以像传递其他专业人士一样简单地传递价值。

import picture from 'linkOfYourImage.png';

function Func() { 
<YourComponent imgLink={picture }/>
}
于 2022-03-01T07:51:35.240 回答