Passing local image uri as props in react-native

2019-07-10 04:56发布

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条回答
Ridiculous、
2楼-- · 2019-07-10 05:32

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'} />
    )
  }  
}
查看更多
登录 后发表回答