1. The setting method before 16.3.0 is as follows
Var HelloMessage = react.createclass ({childMethod: function(){alert(" components communicate successfully "); }, render: Function () {return <div> <h1>Hello {this.props. Name}</h1> <button onClick={this.childMethod}> child </button></div>}}); Var ImDaddyComponent = react. createClass({getDS: The function () {/ / call the components to communicate this. Refs. GetSwordButton. ChildMethod (); }, render: Function (){return (<div> <HelloMessage name="John" ref="getSwordButton" /> <button onClick={this.getds}> </div> ); }}); ReactDOM.render( <ImDaddyComponent />, document.getElementById('correspond') );Copy the code
  1. The setting method after 16.3.0 (including 16.3.0 version) is

Reference: callback 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') } }Copy the code
  1. React Hooks+Typescript Parent component calls child component methods.

The parent component:

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>(" I am the parent component "); 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}> call child </Button> <h1>{text}<h1>)}Copy the code

Child components:

import React, { useImperativeHandle} from 'react'; const ChildComp: React.FC<any> = (props:{onRef:any}) => {useImperativeHandle(props :{onRef:any}) => ({useImperativeHandle) () => {return {childName:' I am a child '}}}); Return (<div> I am a child of </div>)}Copy the code