如何 enable/disable 根据带有 Reactstrap 的复选框输入字段
How to enable/disable input field depending on checkbox with Reactstrap
在我使用 reactstrap 的页面上,我有一个复选框,选中此复选框后,我希望启用输入字段,如果未选中,则禁用输入字段。我将如何去做这件事?这是我当前的代码:
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' 语句有关,或者我遗漏了一些东西。对不起,如果这是一个初学者问题,我仍在努力通过反应。任何帮助将不胜感激。
您需要使用状态来跟踪检查状态
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
回调的范围内定义,您需要使用它来设置其中的状态回调,那么你就可以在其他地方使用检查状态。
我移动了 return 上的输入,但您的 if
也可以与 isChecked
一起使用
在我使用 reactstrap 的页面上,我有一个复选框,选中此复选框后,我希望启用输入字段,如果未选中,则禁用输入字段。我将如何去做这件事?这是我当前的代码:
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' 语句有关,或者我遗漏了一些东西。对不起,如果这是一个初学者问题,我仍在努力通过反应。任何帮助将不胜感激。
您需要使用状态来跟踪检查状态
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
回调的范围内定义,您需要使用它来设置其中的状态回调,那么你就可以在其他地方使用检查状态。
我移动了 return 上的输入,但您的 if
也可以与 isChecked