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

1,738 阅读1分钟
  1. 16.3.0之前的设置方法为
var HelloMessage = React.createClass({
    childMethod: function(){
        alert("组件之间通信成功");
    },
    render: function() {
        return <div> <h1>Hello {this.props.name}</h1>  <button onClick={this.childMethod}>子组件</button></div>
    }
});

// 父组件
var ImDaddyComponent = React.createClass({
    getDS: function(){
        // 调用组件进行通信
        this.refs.getSwordButton.childMethod();
    },
    render: function(){
        return (
                <div>
                    <HelloMessage name="John" ref="getSwordButton" />
                    <button onClick={this.getDS}>父组件</button>
                </div>
        );
    }
});

ReactDOM.render(
        <ImDaddyComponent  />,
        document.getElementById('correspond')
);
  1. 16.3.0之后(包括16.3.0 version)的设置方法为 参考:回调Ref
import React, {Component} from 'react';

export default class Parent extends Component {
    render() {
        return(
            <div>
                <Child onRefProp={this.onRef} />
                <button onClick={this.click} >click</button>
            </div>
        )
    }

    onRef = (ref) => {
        this.child = ref
    }

    click = (e) => {
        this.child.myName()
    }

}

class Child extends Component {
    componentDidMount(){
        this.props.onRefProp(this)
    }

    myName = () => alert('xiaohesong')

    render() {
        return ('woqu')
    }
}
  1. React Hooks+Typescript 中 父组件调用子组件方法.

父组件:

import React, { useState,  useRef } from 'react';
import { Table, Card, Button, } from 'antd';
import ChildComp from './child';

const FComp: React.FC<any> = (props) => {
    let child = useRef();;
    let [text,setText] = useState<string>("我是父组件");
 	
    function onChild(){
        console.log("subMitData", child.current.childMethod());
        let childName = (child.current as any).childMethod();
        setText(childName);
    }
    
    return (
        <ChildComp onRef={child} />
        <Button type='primary' onClick={onChild}>调用子组件</Button>
        <h1>{text}<h1>
    )
}

子组件:

import React, { useImperativeHandle} from 'react';

const ChildComp: React.FC<any> = (props:{onRef:any}) => {
     useImperativeHandle(props.onRef, () => ({
        // onChild 就是暴露给父组件的方法
        onChild: () => {
          return {
          	childName:'我是子组件'
          }
        }
    }));
    return (
        <div>我是子组件</div>
    )			
}