繁体   English   中英

试图使图像在按钮按下时出现-反应本机

[英]Trying to make an image appear upon button press - react native

我只是试图按一个按钮并显示一个图像。 我收到“尝试分配给只读属性”的错误,这是我的代码。

export class calculateRoute extends Component{
  render() {
    return (
      <View>
        <Image
          style={{width: 50, height: 50}}
          source={require('./Alexa.png')}
        />
      </View>
    );
  }
}

然后这是我的按钮代码,应该可以在按下时简单地返回图像。 此代码在不同的类中。

<Button
    onPress={calculateRoute}
    title="Calculate Route"
    color="#841584"
    accessibilityLabel="Button to calculate route"
/>

试试这个代替:

export class calculateRoute extends Component{
  constructor () { 
    super();
    this.state = {showImage: false};
  }

  showImageFunc = () => {
     this.setState({showImage: true});
  }

  render() {
    return (
      <div>
        {this.state.showImage &&
        <View>
          <Image
            style={{width: 50, height: 50}}
            source={require('./Alexa.png')} />
        </View>}
        <Button
          onPress={this.showImageFunc}
          title="Calculate Route"
          color="#841584"
          accessibilityLabel="Button to calculate route" />
      </div>
    );
  }
}

处于组件状态的showImage会告诉渲染器何时显示图像。 希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM