【问题标题】:How to make a checkbox do different things based on their check status True/False如何使复选框根据其检查状态 True/False 执行不同的操作
【发布时间】:2021-11-15 09:48:43
【问题描述】:

好吧,我有一个复选框,当被选中时,它应该保存一些值,当被取消选中时,它应该删除我刚刚取消选中的那个值。从我在Material UI: Checkbox 中看到的内容来看,“受控”部分中有一个“简单的方法”,但它没有用,所以我尝试了其他方法,但也没有用,现在我被卡住了。我看到了类似的问题并尝试了Stackoverflow: How to call 2 functions on onclick of a checkbox?。但显然这也不起作用,因为它来自常规复选框,但我想使用 Material UI 中的复选框。这就是我所拥有的:

Relevant code

const [studentID, setStudentID] = useState([])
const setStudent = (estudiante) => {
  var checkBox = document.getElementById('checkBox');
     if(checkBox.ariaChecked == true){
         console.log("Save data")
         let data = studentID;
         data.push(estudiante);
         setStudentID(data);
         console.log(studentID)
      } 
       else{
         console.log("Delete data")
        }  
}

                <Checkbox  
                color = "primary"
                id = "checkBox"
                onChange = {() => setStudent(estudiante.uid)}
                inputProps={{ 'aria-label': 'controlled' }}
                />

我尝试根据之前从其他帖子中看到的建议对其进行调整,但它不起作用,它只通过一个选项(我没有创建代码来删除刚刚添加的 console.log 的值)

如果我反转它们,这就是我尝试保存数据时的样子(这确实有效,但因为它只做一个或另一个重复)

非常感谢任何提示、建议、文档或帮助。如果需要其他内容,请告诉我。

【问题讨论】:

    标签: reactjs checkbox material-ui


    【解决方案1】:

    首先,您需要控制组件的状态。这意味着您可以管理何时检查和未检查。为此,您需要向组件添加一个“已检查”属性,该属性将成为状态的一部分:

        const [ checked, setChecked ] = useState(false)
    
        <Checkbox  
          checked={checked}
          ...
        />
    

    这部分完成后。现在你有两个选择。您可以按照您尝试的方式进行操作,代码将是这样的:

    const [studentID, setStudentID] = useState([])
    const [ checked, setChecked ] = useState(false)
    
    const setStudent = (estudiante, check) => {
      console.log(estudiante, check) //here you will probably have the inverted value of the check because you are getting the old state. But you can work with it 
      setChecked(prevState => !prevState);
         if(check){
             console.log("Save data")
             let data = studentID;
             data.push(estudiante);
             setStudentID(data);
             console.log(studentID)
          } 
           else{
             console.log("Delete data")
            }  
    }
    
        <Checkbox  
          checked={checked}
          color = "primary"
          id = "checkBox"
          onChange = {() => setStudent(estudiante.uid, checked)}
          inputProps={{ 'aria-label': 'controlled' }}
        />
    

    第二个选项利用 useEffect 钩子:

        const [studentID, setStudentID] = useState([])
        const [ checked, setChecked ] = useState(false)
        const [ id, setId ] = useState(null)
        
        useEffect(() => {
           const setStudent = () => {
            if(checked){
              //your code
            }else{
              //your code
            }
           }
           // IMPORTANT: you need to remember that this useEffect is going to run once when the components just renders. So you need to put a condition here before calling the function 
           if(!isFirstTime){
              setStudent()
           }
        },[checked, id])
    
            <Checkbox  
              checked={checked}
              color = "primary"
              id = "checkBox"
              onChange = {() => {setId(estudiante.uid),setChecked(prevState => !prevState)}}
              inputProps={{ 'aria-label': 'controlled' }}
            />
    

    更新:

    既然你告诉我复选框在地图内。您可以使用数据状态来反映选中的复选框,例如:

    const [studentID, setStudentID] = useState([])
    
    // This is just an example code since I don't see all your code.
    const setStudent = (estudiante) => {
      if (setStudentID.find(studentId => studentId === estudiante.uid)) {
        setStudentID([ ...data, estudiante])
        ... //your code
      }else{
        setStudentID(data.filter(studentId => studentId !== estudiante))
        ... //your code
      }
    }
    
        <Checkbox  
          checked={setStudentID.find(studentId => studentId === estudiante.uid)}
          color = "primary"
          id = "checkBox"
          onChange = {() => setStudent(estudiante.uid)}
          inputProps={{ 'aria-label': 'controlled' }}
        />
    

    【讨论】:

    • 这确实很有帮助,现在我必须让它在地图上工作,因为当我检查一个时,所有这些都会被检查,但这很有帮助
    • 如何让它只选中 1 个复选框,而不是全部:c?
    • 同样有很多方法可以做到这一点。我看不到你那里的所有代码。但我看到你有一组数据,你正在推送学生 ID。如果这个数组处于状态(因为你不应该改变“data.push)”但使用 concat 和 filter 来添加和删除元素,它会很棒。这可能是您的“检查”条件。如果ID在那里检查。如果不是未选中。例如 studentId === estudiante.uid) ...} />.. 我希望这会有所帮助
    • 我不想用更多问题污染这篇文章,所以我提出了一个新问题 check checkbox individually 这也是另一个问题,但相关!
    • 我刚刚在这里编辑了答案。我希望这会有所帮助。告诉我
    猜你喜欢
    • 2011-05-28
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2019-09-26
    • 2011-11-30
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多