【发布时间】:2020-03-22 13:16:13
【问题描述】:
我正在使用 reactjs,试图说当复选框的状态发生变化时,我想这样做或那样。
问题是,我无法恢复复选框状态。
这是来自 checkbox.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>
)
这是我在 form.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,我已将代码更新如下
我将这些行添加到 checkbox.jsx
export const [count, setCount] = useState(false)
export const isChecked = () => true === count
并将 form.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 (如果我删除包含它的行我不再有这个错误)我的问题是,为什么?
如果有人对我有任何提示,我将不胜感激。
谢谢
【问题讨论】:
-
你的
Field组件是什么样的? -
你能创建codesandbox示例吗?