React父组件调用子组件的方法

528 阅读1分钟

工作中有可能会用父组件去调用子组件的某个方法,下面的demo是具体实现方法。

父组件parent.js

import React from 'react';
import Child from './child.js'
export default class parent extends React.Component{
   constructor(props) {
        super(props);
    }
    {
        //将子组件的实例保存在父组件的state当中
        <Child Ref={(childComponent) => this.setState({childComponent})}/>
    } 
    //调用子组件的某个方法
    call = () => {
        let {childComponent} = this.state
        if(childComponent) {
            childComponent.fun() //调用即可
        }
    }
    render() {
        return (
            <Button onClick={this.call}/>
        )   
    }

子组件 child.js

import React from 'react';
export default class child extends React.Component{
   constructor(props) {
        super(props);
        this.state = {}
    }
   async componentDidMount() {
        let {Ref} = this.props
        Ref(this) //调用父组件的方法并传入将当前组件实例
   }
   fun = () => {
        console.log('我是子组件的方法')
   }
}