如何启用/禁用输入字段取决于复选框与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;

我知道我做错了什么,因为它不是我想要的工作方式,我的猜测是它与"如果"语句有关,或者我错过了一些东西。对不起,如果这是一个初学者的问题,我还在努力通过反应的方式。如有任何帮助,不胜感激。

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

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一起工作

最新更新