javascript - React组件回调实现方法有什么区别
问题描述
import React from 'react';
import ChildComponent from './ChildComponent';
class SampleComponent extends React.Component {
sampleCallbackOne = () => {
// does something
};
sampleCallbackTwo = () => {
// does something
};
render() {
return (
<div>
<ChildComponent
propOne={this.sampleCallbackOne}
propTwo={() => this.sampleCallbackTwo()}
/>
</div>
);
}
}
export default SampleComponent;
在这个例子中,我有一个我正在处理的 onClick 事件,我发现我可以通过两种方式成功地将它传递到组件的 props 中。
我想知道这两种方式到底有什么区别,因为它们似乎以相同的方式运作?
为什么两种方式都有效?
解决方案
这是一个看起来很奇怪的共同点。
请参阅处理事件文档中的详细信息
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
handleClick() {
console.log('this is:', this);
}
<button onClick={this.handleClick}>
如果不添加()
后面this.handleClick
,则需要this
在构造函数中进行绑定,否则,您可能需要使用以下两种方法:
A.公共类字段语法
在Create React App中默认启用
handleClick = () => {
console.log('this is:', this);
}
<button onClick={this.handleClick}>
B. 箭头函数
这可能会导致性能问题,不推荐使用,请参阅上面的文档。
// The same on event handling but different in:
<button
onClick={(e) => this.deleteRow(id, e)} // automatically forwarded, implicitly
/>
<button
onClick={this.deleteRow.bind(this, id)} // explicitly
/>
样本
基本上在我们的实践中,我们使用带有参数的公共类字段语法,如下所示:
// No need to bind `this` in constructor
// Receiving params passed by elements as well as getting events of it
handler = (value: ValueType) => (event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
// Do something with passed `value` and acquired `event`
}
<NumberFormat
...
onBlur={this.handler(someValue)} // Passing necessary params here
/>
我们可以handler function
通过传递不同的参数来共享它。
// Justify via keyword of stored content in flat data structure
handler = (value: string) => (event: React.ChangeEvent<HTMLInputElement>, id: ValidationItems) => {
// Do something with
// passed `value`,
// acquired `event`,
// for each element diffenced via `id`
};
<YourComponent
id="ID_1"
value={store.name1}
onChange={this.handler("name1")}
/>;
<YourComponent
id="ID_2"
value={store.name2}
onChange={this.handler("name2")}
/>;
// ... more similar input text fields
推荐阅读
- flutter - Flutter 代码到我的 Flutter 应用程序中的 APK/IPA 文件中
- php - 在php应用程序中打开多个选项卡时速度缓慢
- julia - 错误:构造函数 Pair{Int64,Array{Float64,1}} 需要一个伴随
- mongodb - MongoDB 匹配 $and 不起作用,但 $or 起作用
- javascript - 如何通过发布请求访问车把变量?
- javascript - 将带有 1 个 arg 的函数作为道具传递给子组件
- swift - 表达式类型“字符串”在没有更多上下文的情况下是模棱两可的?
- c# - 如何读取和写入 RFID 作为人机接口设备 C#
- c# - 如何使用 C# 对 MongoDB 集合中所有文档的键值求和
- react-native - 将原生移动屏幕反应到活动屏幕