要在父组件中调用子组件的方法,你需要先在父组件中引入子组件,并创建对应的引用。然后你可以使用该引用来调用子组件的方法。

以下是一个示例:

import React, { Component } from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef(); // 创建子组件的引用
  }

  handleClick = () => {
    this.childRef.current.childMethod(); // 调用子组件的方法
  }

  render() {
    return (
      <div>
        <ChildComponent ref={this.childRef} /> // 将子组件的引用赋值给ref属性
        <button onClick={this.handleClick}>调用子组件方法</button>
      </div>
    );
  }
}

export default ParentComponent;

在上述示例中,我们首先通过React.createRef()创建了一个子组件的引用childRef。然后将该引用赋值给子组件的ref属性,以便在父组件中能够访问子组件的实例。

最后,在父组件的handleClick方法中,我们通过this.childRef.current.childMethod()调用了子组件的方法childMethod()

React.js 父组件调用子组件方法指南

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

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