在ReactJS中如何从父组件调用子组件的方法

14

我有一个需求,需要在Reactjs的父组件中调用子组件的方法。我尝试过使用refs,但是没有成功。请问是否有任何解决方案?谢谢。


可能是从父类调用子类方法的重复问题。 - Nisarg Shah
虽然我来晚了,但我也在学习React,所以我很好奇父组件何时需要调用子组件的方法。您能解释一下吗? - Akshay Raut
5个回答

8

如果使用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>
  );
};

4

1
有时候在使用中,父组件想要触发子组件的某个动作,比如让子组件获得焦点。虽然可以通过在父组件上改变状态变量来实现,但这并不实际。你可能需要创建一个计数器之类的东西,而且这并不是一个好的实现方式。React的forwardRef钩子在官方文档中明确提到了这个焦点使用案例,链接在这里:https://react.dev/reference/react/forwardRef#usage - undefined

3
您可以将 ref 分配给子组件,然后像这样从父组件调用函数:
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 (
           {/*...*/}
      )
   }
}

1

您可以将registerCallback props传递给您的子组件,并在componentDidMount中调用它并传递引用给您的子组件方法,然后您可以随时调用该方法。


1
在您的父类中,您可以创建一个引用。
在构造函数中:
 this.child = React.createRef();

在任何函数中:
execute=(comment)=>{
        this.child.current.addComment();
    }

render(){
        return (
            <div>
                <Messages ref={this.child} comment={this.state.comment}/>
            </div>
        )
    }

在“Message(child)”组件中。
addComment=()=>{
    console.log("Pi ", this.props);

  };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接