gpt4 book ai didi

javascript - reactjs - 为什么通过父属性和组件 onChange 更新表单值状态?

转载 作者:行者123 更新时间:2023-11-29 10:59:19 31 4
gpt4 key购买 nike

我正在阅读 Fullstack React 一书,在他们关于表单验证的示例中,他们创建了自己的 Field 组件(第 204 - 212 页),然后将字段值存储在 Field 状态和父状态中,这让我感到困惑。他们的 Field 组件有一个 value 属性以及一个包含 value 的状态。父组件需要知道每个字段的值,这样才能作为一个整体来做表单验证,所以它也有一个包含value的state。

在 Field 中,它们通过在输入 value 更改时设置 Field 状态以及在 getDerivedStateFromProps value 属性更改:

//(within Field)
getDerivedStateFromProps(nextProps) {
return {value: nextProps.value}
}

onChange = evt => {
const name = this.props.name;
const value = evt.target.value;
const error = this.props.validate ? this.props.validate(value) : false;

this.setState({value, error});

this.props.onChange({name, value, error});
};

它们还通过调用父级的 onInputChange 函数(作为 onChange 属性传递)将另一个方向的值状态同步到父级:

//(within parent component)
onInputChange = ({name, value, error}) => {
const fields = Object.assign({}, this.state.fields);
const fieldErrors = Object.assign({}, this.state.fieldErrors);

fields[name] = value;
fieldErrors[name] = error;

this.setState({fields, fieldErrors});
};

这本书并没有真正解释为什么他们会这样复制状态,只是说,

"There are only two pieces of data that Field will need, the current value and error. Like in previous sections where our form component needed that data for its render() method, so too does our Field component."

还有

"One key difference is that our Field has a parent, and sometimes this parent will want to update the value prop of our Field. To allow this, we’ll need to create a new lifecycle method, getDerivedStateFromProps() to accept the new value and update the state."

我只是一个初学者,但在我看来,将 value 状态完全丢弃在 Field 中并让它作为 prop 传入会更有意义。当输入改变时,调用Field的onChange方法,并在其中调用parent的onInputChange。让 onInputChange 更新有关字段值的父状态,并将字段值作为 Prop 传递给字段。现在的做法似乎有点多余,而且更容易出错。关于他们为什么这样做的任何见解?

最佳答案

没看过书,但在这里我会解释为什么我会写这样的代码。

拥有这两种状态的主要目的是使 Field 组件更通用。

在那种特定情况下,父级恰好也将值保存在他的状态中,并且 Field 组件通过从接收到的 props 更新他的状态成为受控组件在 getDerivedStateFromProps 上。

但是仍然有可能将 Field 组件用作不受控制的组件,那么 Field 的状态将是唯一的真实来源。

在这两种情况下,只有一个真实来源,它保持 React 的做事方式,但是 Field 组件可以以受控和非受控形式使用。

关于javascript - reactjs - 为什么通过父属性和组件 onChange 更新表单值状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414803/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com