我有一个需求,需要在Reactjs的父组件中调用子组件的方法。我尝试过使用refs,但是没有成功。请问是否有任何解决方案?谢谢。
我有一个需求,需要在Reactjs的父组件中调用子组件的方法。我尝试过使用refs,但是没有成功。请问是否有任何解决方案?谢谢。
如果使用React Hooks,您可以使用useRef和useImperativeHandle hooks。
在子组件中,将函数添加到hook中。
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>
);
};
不要这样做 :)
将函数提升到父级并将数据作为 props 传递下去。如果子组件也需要调用该函数,可以将同一个函数作为 props 传递下去。
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 (
{/*...*/}
)
}
}
您可以将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);
};