Load Image in React native from props
我正在尝试通过向下发送标题和图像URL来呈现来自基本组件的图像列表。
如果我渲染这样的图像,一切都可以正常工作:
1 | <Image source={require('../assets/images/myImage.png')} /> |
当我尝试从道具渲染图像时,问题就来了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class ListItem extends Component { render() { return ( <View> <Text>{this.props.title}<Text> <Image source={require(this.props.imageUri)} /> </View> ); } }; ListItem.propTypes = { title: PropTypes.string.isRequired, imageUri: PropTypes.string.isRequired, }; |
结果,我收到下一个错误:
calls to
require expect exactly 1 string literal argument, but this
was found:require(this.props.imageUri) .
我也尝试过使用
渲染图像
1 | <Image source={{uri: this.props.imageUri}} /> |
package.js
1 2 | "react":"16.3.1", "react-native":"https://github.com/expo/react-native/archive/sdk-27.0.0.tar.gz", |
如果将远程图像与
1 2 3 4 | const imageNames = { apple: require('./images/apple.png'), orange: require('./images/orange.png'), }; |
并用他们的名字指代他们:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class ListItem extends Component { render() { return ( <View> <Text>{this.props.title}<Text> <Image source={imageNames[this.props.imageName]} /> </View> ); } }; ListItem.propTypes = { title: PropTypes.string.isRequired, imageName: PropTypes.oneOf(Object.keys(imageNames)), }; // e.g. <ListItem imageName="orange" /> |