gpt4 book ai didi

reactjs - JSX Prop 不应使用 .bind()

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

当我以这种方式进行绑定(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/

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