【问题标题】:Passing local image uri as props in react-native在 react-native 中将本地图像 uri 作为道具传递
【发布时间】:2018-03-24 02:02:04
【问题描述】:

我正在尝试将图像的 uri 作为道具传递,以便我可以在 react-native 上多次重复使用它。但是,这个当前的解决方案提示我 require 应该使用字符串文字。

const ImageButton = ({ source }) => (
    <Image source={require({ source })} />
);

ImageButton.propTypes = {
     uri: PropTypes.string,
};

我也尝试过将 uri 声明为 PropTypes.func,然后做

<Image source={{ source }} />

但图像没有出现。图像 uri 道具的正确实现是什么?

【问题讨论】:

    标签: react-native jsx


    【解决方案1】:

    您需要为需要图像做单独的对象,因为动态定义的字符串是不可能的。

    例如:

    const assets = {
      imageButton: require('./assets/button.jpg'),
    };
    
    const ImageButton = (source) => {
      <Image source={assets[source]} />
    }
    
    class MyComponent extends Component(props) {
      render() {
        return (
          <ImageButton source={'imageButton'} />
        )
      }  
    }
    

    【讨论】:

    • 因此,所有这些都必须在同一个文件中,对吧?我正在尝试这样做,以便从某个地方导入 ImageButton 并将其传递出去,但我认为这是不可能的,因为在没有源的情况下导出 ImageButton 只会导致没有图像被渲染。
    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 2018-05-12
    • 2022-01-24
    • 2023-03-28
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多