有以下代码:
class Component1 extends React.Component {
handleOnClick = () => {
console.log('inside function');
if(typeof this.props.onClick === 'function') {
this.props.onClick(); /* Why this */
}
}
render() {
const {extraClass} = this.props;
return (
<div className={ ${(extraClass)} }>
<Component2 onClick={ this.handleOnClick } />
</div>
);
}
}
我不完全理解检查 'onClick' 属性是否是一个函数然后再次执行它的原因。
据我了解,当我们点击Component2元素时(onClick={ this.handleOnClick }),handleClick已经被执行了。
我错过了什么?
谢谢大家的回复。
最佳答案
Component1
由 div
和 Component2
组成。 Component2
有一个函数,当他被点击时他需要调用它。该函数称为 handleOnClick
,由 Component1
定义。
在 Component1
的 handleOnClick
函数(当单击 Component2
时调用)中,您正在检查 的类型this.props.onClick
。 注意,this.props.onClick
是父级传递给 Component1
的内容(例如,应用
)。
无论如何,当单击 Component2
时,handleOnClick
将会被调用。它是一个函数,我们知道它是一个函数,因为它是在那里定义的。
但是,我们不知道的是,当 Component1
的父级决定使用 Component1< 时,该父级作为 prop(称为
。他可能传递了一个函数(在这种情况下,调用该函数)。但他可能传递了一个字符串,或者可能根本没有传递任何内容(在这种情况下,不要调用它,因为它不是一个函数)。onClick
)传递了什么
这就是为什么您需要检查 this.props.onClick 的类型
。
或者换句话说。我们假设 App
是使用 Component1
的父级。
应用程序
说:
Ok, I want a
Component1
. And when he's clicked (whatever that means), I want him to call this function that I'm passing to him as a prop, which I'll callonClick
.
Component1
说:
So, I've got this prop called
onClick
. But not all of me is "clickable". Only theComponent2
part of me is "clickable." So, I guess, whenComponent2
is clicked, I'll need to make sure I call this function that was passed to me as theonClick
prop. Oh, but I better make sure that my parent who passed me thisonClick
prop actually passed me a function, or else bad things are gonna happen.
Component2
说:
<小时/>So, when I get clicked, I'll just call
handleOnClick
, which belongs toComponent1
. It's his job to figure out what happens there.
更新
OP 在评论中询问了一个示例,说明单击子组件会执行父组件作为 prop 传递的函数。
基本原理是这样的:
Whenever the parent needs to be notified that a child has been clicked, then the parent needs to pass a handler to that child, and the child is responsible for calling that handler whenever he is clicked.
parent 可能“需要被通知”,因为他需要获取该信息并告诉其他 child 去做某事,或者因为他想要更新他的状态,或者因为他想要将其记录到控制台。 parent 可能想知道他的 child 什么时候发生了什么事(在编码中和现实生活中)的原因有很多。作为 prop 传递的函数回调就是实现这一点的方法。
同样的做法不仅限于单击子项时。如果父级需要知道何时将鼠标悬停在子级上,或者何时子级元素具有其值已更改的表单输入,或者何时子级元素向服务器发出请求并获得响应,则可以应用它,等等...
<小时/>为了以基本方式演示这一点,我编写了一个快速代码沙箱供您查看。父级是App
。它有 Component1
作为其子级。事实上,它的子级有 3 个 Component1
实例。 Component1
保留一个计数器,记录他被单独点击的次数。 但是当他被点击时,他也让他的 parent 知道(通过作为 prop 传递的函数回调),以便 parent 可以跟踪所有 child 的点击总数。
最后,我强烈推荐 ReactJS 文档中的这篇文章,标题为 "Lifting State Up" 。它很好地解释了这种亲子互动以及如何/为什么让信息在两者之间来回流动。
关于javascript - react : What's the purpose of checking if a prop is a function to execute it then?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55222438/