javascript - 调用回调函数的函数应该绑定吗?
问题描述
Parent
如果我从to传递一个回调函数GrandChild
,应该handleClick
绑定在Child
and中GrandChild
吗?
父.js
class Parent extends React {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Clicked!');
}
render() {
return (
<Child onClick={this.handleClick} />
);
}
}
Child.js
class Child extends React {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { onClick: callback } = this.props;
callback();
}
render() {
return (
<GrandChild onClick={this.handleClick} />
);
}
}
GrandChild.js
class GrandChild extends React {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { onClick: callback } = this.props;
callback();
}
render() {
return (
<div onClick={this.handleClick} />
);
}
}
解决方案
箭头功能更好。并且上下文this
将自动绑定。
handleClick = () => {}
内联函数不好(可能出现不必要的渲染)。最好是这样:
handleClick = (someData) => this.props.handeClick(someData)
和
onClick={this.handleClick}
推荐阅读
- swagger - 如何将两个 openapi/swagger 模式组合成一个模式
- amazon-web-services - 配置 aws lambda 和 api 网关以返回 image/avif 内容类型的二进制数据
- java - 如何使用 JMS API 从 Solace 侦听器向 Solace 队列发送 NACK?
- excel - Excel中如何处理布尔值?
- azure-devops-server - 为域外的 Azure DevOps 服务器设置第二个应用层
- wordpress - 修复 wordpress 菜单重复问题
- django - Django过滤两条记录并一次更新?
- php - htaccess 中的自定义 404 错误处理程序不适用于不存在的“.php”文件
- python - 以字符串命名函数
- zig - Zig:如何处理可选的错误联合类型?(例如,?std.process.NextError![:0]u8)