mon*_*yjs 16 jsx function-binding reactjs react-jsx
当我以这种方式绑定时如何修复此错误:先前在构造函数中绑定已解决,但这对我来说有点复杂:
{this.onClick.bind(this, 'someString')}>
and
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
Run Code Online (Sandbox Code Playgroud)
ano*_*oop 32
选项1:
使用arrow functions
(使用babel-plugins)PS: - 实验功能
class MyComponent extends Component {
handleClick = (args) => () => {
// access args here;
// handle the click event
}
render() {
return (
<div onClick={this.handleClick(args)}>
.....
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
选项2:不推荐
在渲染中定义箭头函数
class MyComponent extends Component {
render() {
const handleClick = () => {
// handle the click event
}
return (
<div onClick={handleClick}>
.....
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
选项3:
在构造函数中使用绑定
class MyComponent extends Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// handle click
}
render() {
return (
<div onClick={this.handleClick}>
.....
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我建议您在类构造函数中使用绑定。这将避免内联重复(和混乱),并且只会执行一次“绑定”(当组件启动时)。
这是一个示例,您可以在用例中实现更清洁的JSX:
class YourComponent extends React.Component {
constructor(props) {
super(props);
// Bind functions
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleClick() {
this.onClick('someString');
}
onClick(param) {
// That's your 'onClick' function
// param = 'someString'
}
handleSubmit() {
// Same here.
this.handleFormSubmit();
}
handleFormSubmit() {
// That's your 'handleFormSubmit' function
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<p>...</p>
<button onClick={this.handleClick} type="button">Cancel</button>
<button type="submit">Go!</button>
</form>
);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13951 次 |
最近记录: |