react 组件传递函数
<MyComponent onClick={this.handleClick}>
In React, there are several cases where you may want to pass a function (like onClick
) as a prop from a container to a child component — usually in order to let the child notify the parent of some event.
在React中,在某些情况下,您可能希望将作为道具的函数(如onClick
)从容器传递给子组件-通常是为了让子组件将某些事件通知给父组件。
For example:
例如:
Assuming that you will probably need to have access to the parent component’s state
or props
from the child component, you will need to somehow bind the function to the parent component instance.
假设您可能需要从子组件访问父组件的state
或props
,则需要以某种方式将函数绑定到父组件实例。
While there are a few ways to do that, some are better solutions.
虽然有几种方法可以做到这一点,但有些是更好的解决方案。
如何将功能绑定到组件实例? (How Do I Bind a Function to a Component Instance?)
Depending on the syntax and build steps involved, there are many ways to ensure that functions have access to component attributes such as props
and state
.
根据涉及的语法和构建步骤,有很多方法可以确保函数可以访问组件属性(例如props
和state
。