我使用的是来自react-native库的ImageBackground。例如,使用source={ ImageBackground (‘asd.png’)}请求。
但我正在尝试将变量添加到require.
const [image,setImage] = useState('./asd.png')
.then(image => {
setImage(image.path) // gives 'something.png'
});
<ImageBackground source={require(image)></ImageBackground> 但是我得到了错误。第122行的无效调用: require(image)
发布于 2021-05-03 02:01:43
// Declare a varible here...
const img = require('./asd.png')
// Example of a network image
const networkImage = "https://images.pexels.com/photos/799443/pexels-photo-799443.jpeg"
const [image, setImage] = useState(img) // Use it here like this
// Static Image Usage
<ImageBackground
source={image}
style={{ flex: 1, resizeMode: 'cover', justifyContent: 'center' }}>
</ImageBackground>
// Network Image Usage
<ImageBackground
source={{uri : networkImage}}
style={{ flex: 1, resizeMode: 'cover', justifyContent: 'center' }}>
</ImageBackground> 这是使用ImageBackground的正确方式
检查此Snack以查看工作示例
此外,请查看docs以获得更多帮助。
就像医生说的那样
// GOOD (this is also correct)
<Image source={require('./my-icon.png')} />;
// BAD (this is wrong...)
var icon = this.props.active
? 'my-icon-active'
: 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;
// GOOD (this is correct)
var icon = this.props.active
? require('./my-icon-active.png')
: require('./my-icon-inactive.png');
<Image source={icon} />;https://stackoverflow.com/questions/67359482
复制相似问题