【问题标题】:Can't recover Checkbox state with onChange method无法使用 onChange 方法恢复复选框状态
【发布时间】: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示例吗?

标签: reactjs checkbox


【解决方案1】:

所以,如果你想使用输入的状态,你需要使用 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 here 的文档

希望对您有所帮助,如果没有,请分享 codesanbox 或 repl,以便我们调查您的情况。

【讨论】:

  • 感谢您的回复,它帮助我前进!我更新了我的问题,因为我仍然有一些我不太明白的问题。
  • 你不明白 useState 是如何工作的,所以我更新了我的答案。您应该在组件中使用 useState,
  • 好的,我明白了。现在我遇到了另一个问题,即我在 form.jsx 中作为 导入的复选框无法识别 onChange 函数,因为它是在 Checkbox.jsx 文件中声明的。我试过像这样导入组件: (而不是 但它不起作用。你对此有提示吗?
  • 请将您的代码上传到codesandbox或codepen,以便我们查看整个项目
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 2015-04-13
  • 2015-07-25
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
相关资源
最近更新 更多