Passing local image uri as props in react-native

半腔热情 提交于 2019-12-13 14:26:28

问题


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,
};

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

<Image source={{ source }} />

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


回答1:


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

For instance:

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

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

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


来源:https://stackoverflow.com/questions/46704415/passing-local-image-uri-as-props-in-react-native

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!