【问题标题】:React a component is changing an uncontrolled input of type checkbox to be controlled反应一个组件正在改变一个不受控制的复选框类型的输入以被控制
【发布时间】:2019-04-03 22:24:57
【问题描述】:

react 给了我一个警告:“一个组件正在更改复选框类型的不受控输入以进行控制。输入元素不应从不受控切换到受控(反之亦然)。”

但是,我的复选框是通过 state 属性更改的。我错过了什么明显的东西吗?

    import React from 'react';

// Components
import Checkbox from './checkbox';
import HelpBubble from './helpBubble';

export default class CheckboxField extends React.Component {


    constructor(props) {
        super(props);
        this.state = {value: props.value};
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        this.setState({value: event.target.value});
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.props.value) {
            this.setState({value: nextProps.value});
        }
    }

    render() {
        const {label, meta = {}, help, disabled, required, onChange} = this.props;

        return (
            <label className="checkbox-wrap form-field">
                <Checkbox
                    disabled={disabled}
                    type="checkbox"
                    onChange={(event) => {
                        onChange(event, !this.state.value);
                    }}
                    checked={this.state.value}/>
                {label && (
                    <div className="checkbox-label">
                        {label}
                        {required && <div className="form-field__required"/>}
                    </div>
                )}
                {help && <HelpBubble help={help}/>}
                {meta.error && meta.touched && (
                    <div className="input-error">{meta.error}</div>
                )}
            </label>
        );
    }}

父组件: handleChangeParams(键,值) } /> 处理更改参数更改模型中的值并调用服务器。根据服务器结果,该值可能会发生变化。

提前致谢。

【问题讨论】:

  • 如果没有您也发布Checkbox 组件和CheckboxField 的父组件,我们无法确定
  • onChange={(event) =&gt; { onChange(event, !this.state.value); }} 不确定,为什么?
  • 就像@Ved 暗示的那样,处理程序是错误的。但这看起来有更多的问题。我建议您检查reactjs.org/docs/forms.html 使用他们的示例并从那里获取。
  • @PeterVanDrunen 我添加了一些关于父组件的信息。下面的答案似乎有效,但如果我做错了什么,我仍然很高兴:)
  • @Ved 调用“onChange”时,状态值仍然是“先前”值。实际上它根本没有改变,除非由父元素设置。

标签: javascript reactjs


【解决方案1】:

如果你的状态被初始化为 props.valuenull React 将认为你的 Checkbox 组件是不受控制的。

尝试设置您的初始状态,使值永远不会是null

this.state = { value: props.value || "" };

【讨论】:

  • 这需要记录在 React 的某个地方!
【解决方案2】:

如果您使用的是复选框,react 也不会喜欢字符串,因此请尝试

this.state = { checkboxValue: props.checkboxValue || false };

【讨论】:

    【解决方案3】:

    上面的代码sn-p有一点值得注意。当您从 props 在构造函数中设置状态时,最好将状态设置为“受控”值,即有形值,例如 int、float、string、array、map 等。您得到的错误是props.value 设置为 null 的结果

    所以,考虑像这样设置你的构造函数状态:

    this.state = {
        value: props.value ? props.value : 'empty'
    }
    

    这里发生的是检查props.value 是否有值,如果有则将状态设置为props.value,如果props.value 为空,则将状态设置为字符串:`'empty'

    【讨论】:

      【解决方案4】:

      另一种简单的方法是 !! 你的 props.checkboxValue 值。这样即使未定义,!!props.checkboxValue 也会解析为 false。

      this.state = { checkboxValue: !!props.checkboxValue };

      【讨论】:

        【解决方案5】:

        在我的例子中,我使用我的 redux 商店中的道具来设置复选框是否被选中,只需将属性默认为 false 对我有用。

        例如

        const MyComponent = ({
          somePropFromRedux
        }) => {
          return <thatThridPartyCheckboxComponent checked={somePropFromRedux} />
        }
        

        变为(唯一的变化是在第 2 行添加 = false

        const MyComponent = ({
          somePropFromRedux = false
        }) => {
          return <thatThridPartyCheckboxComponent checked={somePropFromRedux} />
        }
        

        【讨论】:

          【解决方案6】:

          不要在输入框中使用e.target.checkedonChange eventHandler 方法。

          正确方法:

            const [isChecked, setCheck] = useState(false);
           const handler = (e) => {
              setCheck(!isChecked);
            };
          
           <input
                  type="checkbox"
                  checked={isChecked}
                  onChange={handler}
                />
          

          【讨论】:

            猜你喜欢
            • 2022-08-02
            • 2019-06-19
            • 1970-01-01
            • 2020-08-21
            • 2018-08-28
            • 2021-05-21
            • 2020-11-04
            • 2019-11-16
            • 1970-01-01
            相关资源
            最近更新 更多