将本地图像uri作为props传递给react-native [英] Passing local image uri as props in react-native

查看:306
本文介绍了将本地图像uri作为props传递给react-native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像的uri作为prop传递,因此我可以在react-native上多次重用它.但是,当前的解决方案提示我require必须使用字符串文字.

I'm trying to pass the uri of an image as prop so I can reuse it several times on react-native. However, this current solution prompts me that require should use string literals.

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

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

我也尝试过将uri声明为PropTypes.func,并这样做

I've also tried declaring uri as a PropTypes.func, and doing

<Image source={{ source }} />

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

but the image doesn't appear. What's the correct implementation of an image uri prop?

推荐答案

由于动态定义的字符串无法实现,因此您需要为需要图像的对象做一个单独的对象.

You need to do separate object for requiring images since it's not possible with dynamically defined strings.

例如:

const assets = {
  imageButton: require('./assets/button.jpg'),
};

const ImageButton = (source) => {
  <Image source={assets[source]} />
}

class MyComponent extends Component(props) {
  render() {
    return (
      <ImageButton source={'imageButton'} />
    )
  }  
}

这篇关于将本地图像uri作为props传递给react-native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆