正在选中的更新复选框值 - 本机反应



我有一个复选框:

 <CheckBox 
   checked={this.state.preference} 
   onPress={() => this.setState({
     preference: !this.state.preference
   })}
 />

最初,我希望根据我正在获取的数据选中该复选框。我有一个值为 0 的首选项字段,所以我把:

{
  this.props.data.profile && this.props.data.profile.preference== 0 ? 
    this.state.preference = false : this.state.preference= true
}

但是现在在Press上,this.state.preferences不会改变,因为它仍然获得profile.ppreferences值。

我该如何解决这个问题?最初,复选框是根据this.props.data.profile.preference选中的,然后按我可以更改吗?

 constructor(props) {
  super(props);
  this.state = {
      showForm: 0,
      active: true,  
      emailPreference: true,
  };

所以在复选框之前,我有: 如果this.props.data.profile && this.props.data.profile.preference == 0,则使emailPpreferences为假,否则emailPpreferences为true。

然后根据电子邮件首选项添加检查。但是一旦它得到值,即使 onPress 我将状态从 true 更改为 false,反之亦然。它不会更新。

你应该总是使用 setState({ ppreferences: "hello }( 来更改状态,永远不要直接更改 this.state。第二个代码片段中的三元也按错误的顺序排列,您应该在对象中使用冒号而不是 = 。总的来说,我认为试试这个:

{
  this.setState({
      preference: this.props.data.profile && this.props.data.profile.preference == 0 ? false : true
  })
}

最新更新