繁体   English   中英

本机反应 - state 如何与按钮一起使用

[英]react native - how state works with buttons

我是 React Native 的新手,最近在我的代码中实现了 state。

我目前有 2 个按钮:一个用于在我的应用程序中打开相机,一个用于关闭相机。

我想知道的是:我可以根据按下按钮的时间更改按钮的 state 吗? 例如:如果我按下一个按钮,该按钮将录制一段视频,但如果我再次按下同一个按钮,它就会停止。 我目前只知道如何在这种情况下通过使用 2 个不同的按钮来更改 state,而不是在单个按钮中更改 state。

这是我到目前为止用于打开和关闭相机的 2 个按钮的代码:

class CameraButton extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showCamera: false,
    };
  }

  showCamera = () => this.setState({showCamera: true});
  hideCamera = () => this.setState({showCamera: false});

  render() {
    return (
      <View style={styles.container}>
        <Button
          onPress={this.showCamera}
          title="click me to open the camera!"
          color="#841584"
        />
        {this.state.showCamera && <DeviceCamera />}
        <Button
          title="click me to close the camera!"
          onPress={this.hideCamera}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

export default CameraButton;

这很简单。 我有没有办法让用户按下“单击我打开相机按钮”,然后当他们打开相机时,而不是让另一个按钮关闭相机? 我想让用户点击“点击我打开相机”。 按钮(再次)并更改此按钮的 state 如果他们再次单击它? 这对于概念证明来说更是如此,这样我就可以知道将来的使用——我需要能够在 React Native 中实际录制/停止录制视频,我需要理解这个概念。

您可以使用切换 state 变量的 bool 值。

ShowButton = () => {
let prevState = this.state.showCamera;
this.setState({showCamera: !prevState}); //It will toggle the value
}

试试这个,让我知道它是否适合你?

解决方案

class CameraButton extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showCamera: false
    };
  }

  showCamera = () => this.setState({ showCamera: true });
  hideCamera = () => this.setState({ showCamera: false });

  render() {
    return (
      <View style={styles.container}>
        <Button
          onPress={this.state.showCamera ? this.hideCamera : this.showCamera}
          title={this.state.showCamera ? "Hide Camera!" : "Show Camera"}
          color="#841584"
        />
        {this.state.showCamera && <DeviceCamera />}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  }
});

export default CameraButton;

希望能帮助到你:)

你只需要根据showCamera state改变ButtononPress事件即可。

       <Button
              onPress={this.state.showCamera ? this.hideCamera : this.showCamera}
              title={this.state.showCamera 
                ? "click me to hide the camera!"
                : "click me to open the camera!"}
              color="#841584"
       />

暂无
暂无

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

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