Skip to content

父组件调用子组件的函数

JS

const { Component } = React;

class Parent extends Component {
  constructor(props) {
    super(props);
    this.child = React.createRef();
  }

  onClick = () => {
    this.child.current.getAlert();
  };

  render() {
    return (
      <div>
        <Child ref={this.child} />
        <button onClick={this.onClick}>Click</button>
      </div>
    );
  }
}

class Child extends Component {
  getAlert() {
    alert('getAlert from Child');
  }

  render() {
    return <h1>Hello</h1>;
  }
}

ReactDOM.render(<Parent />, document.getElementById('root'));

TS

import React, {forwardRef, useRef, useImperativeHandle} from "react";

interface CanShowAlert {
  showAlert(): void;
}

export default function App() {
  const childRef = useRef<CanShowAlert>(null);
  return (
    <div className="container">

      <Child ref={childRef} />
      <button
        onClick={() => { childRef.current?.showAlert() }}
      >
        Call Function
            </button>

    </div>
  )
}

// 注意,这里Child的类型不行就直接省略,删除掉
// const Child: React.FC<Props> = forwardRef<CanShowAlert, {}>((props, ref) => {

const Child = forwardRef<CanShowAlert, {}>((props, ref) => {
    useImperativeHandle(
        ref,
        () => ({
             showAlert() {
                alert("Child Function Called")
                console.log('hello world')
            }
        }),
    )
    return (
        <div>Child Component</div>
    )
})

Ref

https://stackoverflow.com/questions/37949981/call-child-method-from-parent https://stackoverflow.com/questions/66363320/call-child-function-from-parent-in-reactjs-using-useref