无法使用 onChange 方法恢复复选框状态



我正在使用reactjs,试图说当复选框的状态发生变化时,我想做这个或那个。

问题是,我无法恢复复选框状态。

这是复选框中的复选框组件。jsx:

const Checkbox = ({ input, label, disabled }) => (
<div>
<Input
{...input}
id={input.name}
checked={input.value}
type="checkbox"
disabled={disabled}
/>
<Label htmlFor={input.name}>{label}</Label>
</div>
)

以下是我在表单中呈现复选框的代码。jsx:

<div className="col-md-3">
<Field 
name="checkboxName"
type="checkbox"
component={Checkbox}
label="checkbox name"
onChange={changeCheckboxValue(Checkbox.state.value)}
/>
</div>

Checkbox.jsx中我的changeCheckboxValue代码(仅打印参数中传递的值(:

export const changeCheckboxValue = (value) => {
console.log(value)
}

我精确地说,这个形式不是一个类,而是一个常量。

我不是reactjs开发人员,很难理解这个错误的来源。

更新:

感谢Davo Mkrtchyan,我已经按照更新了我的代码

我将这些行添加到复选框中。jsx

export const [count, setCount] = useState(false)
export const isChecked = () => true === count 

并将表单.jsx中的复选框字段呈现更改为:

<div className="col-md-3">
<Field
name="checkboxname"
type="checkbox"
component={Checkbox}
label="Travailleur handicapé"
onClick={() => setCount(!count)}
/>
</div>

现在我得到以下错误:

Uncaught Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

我知道这可能是由于useState(如果我删除包含它的行,我就不再有这个错误了(,我的问题是,为什么?

如果有人能给我任何提示,我将不胜感激。

感谢

因此,如果您想使用Input的状态,您需要使用useState((钩子,类似于以下内容:

export const CheckBoxComponent = (props) => {
const [check,setChecked] = useState(false);
const onChange = () => {
setChecked(!check)
};
const handlerFunction = () =>{
if(checked){
//do stuff 
} else {
// do other stuff
};
}
return (
<Input
{...input}
id={input.name}
checked={check}  // <----- check is current state
type="checkbox"
onChange={onChange} // <----- onChange will update current state
disabled={disabled}
/>)
}

你可以在这里查看useState的文档

我希望这能有所帮助,如果没有,请分享codesanbox或repl,这样我们就可以调查你的案件。

最新更新