簡體   English   中英

如何確定您的狀態中選中了哪個復選框?

[英]How can I determine which checkbox was selected in your state?

我正在使用react-native-elements復選框,我有2個復選框,我只想選擇其中一個,我設法做到了這一點,但是我試圖只用console.log復選框,但由於它們不起作用有兩種不同的狀態,那么如何確定使用該狀態在我的應用程序中選中了哪個框? 這是代碼:

初始狀態:

state: {
  single: false,
  married: false
}

復選框:

 <CheckBox title="Single"
              checked={this.state.single}
              onPress={() => this.setState({ single: !this.state.single, 
              married: false})}/>

 <CheckBox title="Married"
              checked={this.state.married}
              onPress={() => this.setState({ married: !this.state.married, 
              single: false})}/>

我有一個api,我想在其中發布數據,它具有maritalStatus屬性,我想根據復選框將已婚或單身作為字符串值發送

看起來它們是異或運算。 您需要通過查看單擊按鈕的過去狀態來設置每個人的當前狀態。

http://www.howtocreate.co.uk/xor.html

單:

{single: !this.state.single, married: this.state.single}

已婚

{single:this.state.married, married: !this.state.married}

確實存在三個條件。

  1. 用戶尚未選擇框
  2. 用戶選擇單
  3. 用戶選擇已婚。

如果您有驗證,這意味着用戶必須選中一個框,則可以取消第一個條件。 由此,一旦用戶選擇了一個盒子,就可以知道僅一個盒子的狀態,從而知道他們的選擇。 因此,如果您有一個檢查驗證的按鈕,則可以執行以下操作。

<Button 
  title={'check married status'}
  onPress={() => {
   if (!this.state.single && !this.state.married) {
     alert('Please check a box)
   } else {
     // we only need to check one of them
     let marriedStatus = this.state.married ? 'married' : 'single';
     alert(`You are ${marriedStatus}`)
     // then you can do what you want with the marriedStatus here
   }
  }}
/>

我認為您不需要為此管理兩個狀態。 在這種情況下,一個人可以結婚也可以單身。 所以你需要做這樣的事情

如果您想同時選中兩個復選框,則在加載時

state: {
  single: void 0,
}


<CheckBox title="Single"
              checked={this.state.single}
              onPress={() => this.setState({ single: !this.state.single})}/>

 <CheckBox title="Married"
              checked={this.state.single !== undefined && !this.state.single}
              onPress={() => this.setState({ married: !this.state.single})}/>

或者如果一個檢查

state: {
  single: true,
}


<CheckBox title="Single"
              checked={this.state.single}
              onPress={() => this.setState({ single: !this.state.single})}/>

 <CheckBox title="Married"
              checked={!this.state.single}
              onPress={() => this.setState({ married: !this.state.single})}/>

希望這對您有用。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM