Javascript 在react native中未显示来自状态的图像

Javascript 在react native中未显示来自状态的图像,javascript,react-native,react-native-android,Javascript,React Native,React Native Android,我已将图像名称保存在状态中,但当我尝试显示它们时,会出现错误“Invalid call require('./assets/'+this.state.img1)”(但当我将图像名称直接放入源中时,它将开始工作。例如: 我还提醒该州,它有相同的图像名称 render() { return ( <TouchableOpacity onPress={this.onItemPressed} style={styles.container}> <Image

我已将图像名称保存在状态中,但当我尝试显示它们时,会出现错误“Invalid call require('./assets/'+this.state.img1)”(但当我将图像名称直接放入源中时,它将开始工作。例如: 我还提醒该州,它有相同的图像名称

  render() {
  return (
  <TouchableOpacity onPress={this.onItemPressed} style={styles.container}>

       <Image
        style={styles.stretch}
        source={require('./assets/'+this.state.img1)}
      />
       <Image
        style={styles.stretch}
        source={require('./assets/'+this.state.img2)}
      />
    </TouchableOpacity>
  )
}
render(){
返回(
)
}
根据:
为了使其工作,必须静态地知道require中的图像名称。

//很好
;
//坏的
var icon=this.props.active?'my icon active':'my icon inactive';
;
//好
var icon=this.props.active
?需要(“./my icon active.png”)
:require('./my icon inactive.png');
;
您可以做的是构建映射/对象:

const myImages={
img1:require('/path/to/img1'),
img2:require('/path/to/img2'),
};
render(){
返回(
)
}
要使其工作,
this.state.img1
this.state.img2
必须是对象
myImages
中的一个键,根据:
为了使其工作,必须静态地知道require中的图像名称。

//很好
;
//坏的
var icon=this.props.active?'my icon active':'my icon inactive';
;
//好
var icon=this.props.active
?需要(“./my icon active.png”)
:require('./my icon inactive.png');
;
您可以做的是构建映射/对象:

const myImages={
img1:require('/path/to/img1'),
img2:require('/path/to/img2'),
};
render(){
返回(
)
}

要使其正常工作,
this.state.img1
this.state.img2
必须是对象
myImages
中的一个键。请尝试使用字符串模板:
要求(`./assets/${this.state.img1})
。请告诉我它是否工作。不。这是语法错误。这是否回答了您的问题?请尝试使用字符串模板:
要求(`./assets/${this.state.img1}`)
。让我知道它是否有效..不,这是语法错误这能回答你的问题吗?