gpt4 book ai didi

javascript - React 类组件异常 this 对方法的绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 08:18:46 25 4
gpt4 key购买 nike

例如下面的类组件:

class Todo extends Component {
state = {
list: ["First Todo"],
text: ""
};

handleSubmit(e) {
e.preventDefault();
if (this && this.setState) {
console.log("this present in handleSubmit");
this.setState(prevState => ({
list: prevState.list.concat(this.state.text),
text: ""
}));
} else {
console.log("this not present in handleSubmit");
}
}

handleChange(e) {
if (this && this.setState) {
console.log("this present in handleChange");
this.setState({
text: e.target.value
});
} else {
console.log("this not present in handleChange");
}
}

removeItem(index) {
if (!this || !this.setState) {
console.log("this not present in removeItem");
}
console.log("this present in removeItem");
const list = this.state.list;
list.splice(index, 1);
this.setState({ list });
}

render() {
return (
<div>
<h1>TODO LIST</h1>
<form onSubmit={this.handleSubmit}>
<input value={this.state.text} onChange={e => this.handleChange(e)} />
<button>Add</button>
<ol>
{this.state.list.map((item, index) => {
return (
<li key={index}>
{item}
<button onClick={() => this.removeItem(index)}>Delete</button>
</li>
);
})}
</ol>
</form>
</div>
);
}
}

this 绑定(bind)到类方法的行为不一致。

玩转组件我们会发现,handleChangeremoveItem 具有正确的 this 上下文,而 handleSubmitthis 上下文为 undefined

这两个具有正确 this 上下文的函数在 jsx 中都表示为箭头函数。如下所示:

<input value={this.state.text} onChange={e => this.handleChange(e)} />

虽然 handleSubmit 作为函数本身传递。如下所示:

<form onSubmit={this.handleSubmit}>

但是,我真的不知道为什么会这样。因为,根据我的理解,函数的传递方式应该无关紧要,即作为函数本身或如上所述的箭头表示。

Edit React example

最佳答案

箭头函数有词法this。这意味着 its value is determined by the surrounding scope .因此,当您使用它而不是 class methods 时,this 值将被映射到实例。但是当您调用 this.onSubmit 时,this 将引用本地范围而不是实例本身。要解决此问题,请使用 arrow functionsbind 构造函数中的 onSubmit 方法。

constructor(props){
super(props)
this.onSubmit = this.onSubmit.bind(this)
}

关于javascript - React 类组件异常 this 对方法的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463398/

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