gpt4 book ai didi

reactjs - 在 React 中对类属性使用箭头函数。不清楚

转载 作者:行者123 更新时间:2023-12-03 13:45:29 24 4
gpt4 key购买 nike

我发现箭头函数功能被用作 React 组件中的 Class 属性。在网上查看,我发现它使代码更具可读性,并且由于箭头函数功能,我们不必在构造函数内绑定(bind)handlEvents函数。

即使在对类属性使用箭头函数时,我仍然必须使用绑定(bind)方法,如下面的代码所示。当我删除构造函数中的绑定(bind)时,它在控制台中显示错误警告:组件正在更改要控制的文本类型的不受控制的输入。并且表单错误也不会显示

class Contact extends Component {
constructor(props) {
super(props);

this.handleBlur = this.handleBlur(this);
}

handleBlur = evt => field => {
this.setState({
touched: { ...this.state.touched, [field]: true }
});

render() {
return(
<Form onSubmit={this.handleSubmit}>
<FormGroup row>
<Label htmlFor="firstname" md={2}>
First Name
</Label>
<Col md={10}>
<Input
type="text"
id="firstname"
name="firstname"
placeholder="First Name"
valid={errors.firstname === ""}
invalid={errors.firstname !== ""}
value={this.state.firstname}
onBlur={event => {
this.handleBlur("firstname");
}}
onChange={this.handleInputChange}
/>
<FormFeedback>{errors.firstname}</FormFeedback>
</Col>
</FormGroup>
</Form>
)

}

最佳答案

当前的 ECMAScript 并未正式支持类中早期绑定(bind)的箭头函数。

使用箭头函数作为类方法 will get you in trouble当你的类被继承并且子类想要重写父类方法时。

但是,我想说在你的 React 组件中使用它们是非常安全的,因为你不会在这里遇到继承问题,因为使用 React 你通常不会进一步从你自己的组件继承(参见 Composition vs Inheritance ):

At Facebook, we use React in thousands of components, and we haven’t found any use cases where we would recommend creating component inheritance hierarchies.

丹·阿布拉莫夫是 using arrow functions在组件方法中也是如此,但他建议仅在需要早期绑定(bind)时才使用它。

While it’s still experimental, in my experience it solves the problem fairly nicely. It’s not at all React-specific: I find it useful in any classes that deal with asynchrony and callbacks because the binding problem is common for all JavaScript, not just React. We enabled this syntax proposal in the whole Facebook codebase, and if it gets dropped or changes, we’ll make sure to release an automated codemod to migrate to the new syntax (or, worst case, transform it back into bind calls in constructor).

但是,正如 Dan 指出的那样,为了安全起见,请坚持在构造函数中进行早期绑定(bind):

If you want to stick to the language standard, manual binding in constructor is the way to go. It’s tedious but usually you only want to do this for event handlers, and by convention you start them with handle* in React, so it’s not too hard to remember to bind those.

<小时/>

更新:关于您的案例:

在您的情况下,您可以使用 Anshul Bansal 提供的解决方案,将字段名称传递到 handleBlur 中,并在将返回的函数作为事件回调传递时使用闭包中的字段变量.

或者您可以通过evt.target直接访问字段的输入名称(代码未测试)。

handleBlur = evt => {
const field = evt.target.name;
this.setState({
touched: { ...this.state.touched, [field]: true }
});

关于reactjs - 在 React 中对类属性使用箭头函数。不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53316511/

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