【问题标题】:How to enable/disable input field depending on checkbox with Reactstrap如何根据 Reactstrap 的复选框启用/禁用输入字段
【发布时间】:2021-10-27 14:15:03
【问题描述】:

在页面上我有reststrap,我有一个复选框,当检查这个复选框时,我想要启用的输入字段,如果未选中,则禁用输入字段。我该怎么做呢?这是我当前的代码:

import {
    Input,
    FormGroup,
    FormText,
    Form,
    Label,
    Button,
  } from "reactstrap";

function HelloWorld() {
   let mpinput;
      if ((e) => e.target.checked === true) {
        mpinput = <Input type="text" name="pmInput" id="pmInput"/>
      } else {
        mpinput = <Input type="text" name="pmInput" id="pmInput" disabled />
      }
   return (
   ...
   <FormGroup check>
       <Label check>
           <Input type="checkbox" id="mpCheckbox" onChange={(e) => console.log(e.target.checked)} />
           <Label for="mpinput">Input Field</Label>
           {mpinput}
       </Label>
   </FormGroup>
   )
}
export default HelloWorld;

我知道我做错了什么,因为它没有按我希望的方式工作,我的猜测是它与“if”语句有关,或者我遗漏了一些东西。抱歉,如果这是一个初学者问题,我仍在努力通过反应。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs reactstrap


    【解决方案1】:

    您需要使用状态来跟踪检查状态

    function HelloWorld() {
       const [isChecked, setIsChecked] = React.useState(false)
    
       return (
       ...
       <FormGroup check>
           <Label check>
               <Input type="checkbox" id="mpCheckbox" onChange={(e) => setIsChecked(e.target.checked)} />
               <Label for="mpinput">Input Field</Label>
               <Input type="text" name="pmInput" id="pmInput" disabled={isChecked} />
           </Label>
       </FormGroup>
       )
    }
    export default HelloWorld;
    

    在您的代码中,if 无法访问e 变量,它仅定义在onChange 回调的范围内,您需要使用它来设置该回调内部的状态,然后您就可以在其他地方使用检查状态。

    我在返回时移动了输入,但您的 if 也可以与 isChecked 一起使用

    【讨论】:

    • 非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多