【发布时间】:2017-11-24 02:48:35
【问题描述】:
我需要从父组件调用子组件方法 在 reactjs 中。我曾尝试使用 refs 但无法做到。任何人都可以提出任何解决方案。 谢谢。
【问题讨论】:
-
虽然我已经很晚了,但我也在学习 React,所以我很好奇父母需要调用子方法的情况。你愿意解释一下吗?
标签: reactjs
我需要从父组件调用子组件方法 在 reactjs 中。我曾尝试使用 refs 但无法做到。任何人都可以提出任何解决方案。 谢谢。
【问题讨论】:
标签: reactjs
不要:)
将函数提升到父级并将数据作为道具向下传递。您可以向下传递相同的函数,以防孩子也需要调用它。
【讨论】:
你可以给子组件分配一个引用,然后像父组件一样调用函数形式
class Parent extends React.Component {
callChildFunction = () => {
this.child.handleActionParent(); ///calling a child function here
}
render(){
return (
<div>
{/* other things */}
<Child ref={(cd) => this.child = cd}/>
</div>
)
}
}
class Child extends React.Component {
handleActionParent = () => {
console.log('called from parent')
}
render() {
return (
{/*...*/}
)
}
}
【讨论】:
如果使用 React Hooks,你可以使用 useRef 和 useImperativeHandle hooks。
在子组件中,添加钩子中的函数。
const Child = forwardRef((props, ref) => {
const printSomething = () =>{
console.log('printing from child function')
}
useImperativeHandle(ref, () => ({
printSomething: printSomething
}));
return <h1>Child Component</h1>;
});
使用 ref 从父级调用公开的函数。
const Parent = () => {
const childRef = useRef();
return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.printSomething()}>Click</button>
</div>
);
};
【讨论】:
您可以将registerCallback props 传递给您的孩子并从componentDidMount 调用它并将引用传递给您的孩子组件方法,然后您可以随时调用它的方法
【讨论】:
你可以在你的父母中创建一个参考
在构造函数中:
this.child = React.createRef();
在任何函数中:
execute=(comment)=>{
this.child.current.addComment();
}
render(){
return (
<div>
<Messages ref={this.child} comment={this.state.comment}/>
</div>
)
}
在消息(子)组件中
addComment=()=>{
console.log("Pi ", this.props);
};
【讨论】: