【发布时间】:2015-12-17 01:52:57
【问题描述】:
我正在尝试访问父组件中子组件的方法。
首先我想使用 refs 而不是 this.props.children,但是只有在我的组件中使用它们时才能访问 refs。
用这个的时候,好像不行:
<Parent>
<Child ref="testChild" />
</Parent>
在我的父组件中,我无法访问 this.refs.testChild - 因此我必须使用 this.props.children 访问此组件。
但是:当使用this.props.children 访问它们时,我无法调用孩子的方法。
例子:
// Child.jsx
{
customMethod() {},
render() {... some stuff ...}
}
// Parent.jsx
{
callChildrenMethods() {
this.props.children.map((child)=>{
console.log(child.props); // Props Object
console.log(child.customMethod); // Undefined
});
},
render() {return(<div>{this.props.children}</div>)}
}
如您所见:customMethod 未定义。有什么简单的方法可以访问这些方法吗?更好的方法是使用refs 访问孩子,但在我的情况下这是不可能的。
【问题讨论】:
-
你想通过从父母传递道具到孩子或使用商店来实现这是不可能的?
标签: reactjs