为什么我需要在 onChange
处理程序中为 handleChange
添加 bind(this)
以获得正确的 this
关键字?
class SearchBar extends React.Component{
constructor(props){
super(props);
}
handleChange(){
console.log(this)
this.props.onUserInput(
this.refs.filterTextInput.value,
this.refs.inStockOnlyInput.checked
);
}
render() {
return (
<form>
<input
type="text"
placeholder="Searrch...."
value={this.props.filterText}
ref="filterTextInput"
onChange={this.handleChange.bind(this)} // the bind(this) is needed if not this in handleChange became undefined
/>
<p>
<input
type="checkbox"
checked={this.props.inStockOnly}
ref="inStockOnlyInput"
onChange={this.handleChange}
/>
{' '}
only show products in stock
</p>
</form>
);
}
}
最佳答案
这是因为使用新的 React extends Component
语法,他们在组件创建时删除了自动绑定(bind),就像在旧的 .createClass
语法中一样。默认情况下,使用 es2015 中的 class 语法,你必须将 this 绑定(bind)到一个方法才能使用 this 类,所以这里也是如此。
您可以在 this changelog 中阅读 React 做出此更改的决定。博文。
关于javascript - 带有 "this"关键字的 React 类行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875132/