问题
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