当我以这种方式进行绑定(bind)时如何修复此错误:以前在构造函数中的绑定(bind)已解决,但这对我来说有点复杂:
{this.onClick.bind(this, 'someString')}>
和
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
最佳答案
选项 1:
使用箭头函数
(使用 babel-plugins)
PS:- 实验性功能
class MyComponent extends Component {
handleClick = (args) => () => {
// access args here;
// handle the click event
}
render() {
return (
<div onClick={this.handleClick(args)}>
.....
</div>
)
}
}
选项 2:不推荐
在渲染中定义箭头函数
class MyComponent extends Component {
render() {
const handleClick = () => {
// handle the click event
}
return (
<div onClick={handleClick}>
.....
</div>
)
}
}
选项 3:
在构造函数中使用绑定(bind)
class MyComponent extends Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// handle click
}
render() {
return (
<div onClick={this.handleClick}>
.....
</div>
)
}
}
关于reactjs - JSX Prop 不应使用 .bind(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40773220/