在 React 中,父组件可以通过 ref 来调用子组件的方法。

方法一:使用回调函数将子组件的方法传递给父组件

在子组件中定义一个方法,并将该方法作为参数传递给父组件的回调函数。父组件可以通过调用该回调函数来调用子组件的方法。

// 子组件
class ChildComponent extends React.Component {
  myMethod() {
    // 子组件的方法
  }
  
  render() {
    return (
      <div>
        {/* 子组件的内容 */}
      </div>
    );
  }
}

// 父组件
class ParentComponent extends React.Component {
  handleChildMethod(childMethod) {
    // 父组件调用子组件的方法
    childMethod();
  }
  
  render() {
    return (
      <div>
        <ChildComponent ref={childRef => this.childRef = childRef} />
        <button onClick={() => this.handleChildMethod(this.childRef.myMethod)}>调用子组件方法</button>
      </div>
    );
  }
}

方法二:使用 React.createRef() 创建 ref 并将其传递给子组件

在父组件中使用 React.createRef() 创建一个 ref,并将该 ref 传递给子组件的 ref 属性。然后,可以通过该 ref 来访问子组件的方法。

// 子组件
class ChildComponent extends React.Component {
  myMethod() {
    // 子组件的方法
  }
  
  render() {
    return (
      <div>
        {/* 子组件的内容 */}
      </div>
    );
  }
}

// 父组件
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }
  
  handleChildMethod() {
    // 父组件调用子组件的方法
    this.childRef.current.myMethod();
  }
  
  render() {
    return (
      <div>
        <ChildComponent ref={this.childRef} />
        <button onClick={() => this.handleChildMethod()}>调用子组件方法</button>
      </div>
    );
  }
}

通过上述两种方法,父组件就可以调用子组件的方法了。

React 父组件如何调用子组件方法

原文地址: https://www.cveoy.top/t/topic/quSk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录