React访问子组件方法

599 阅读1分钟

1. 类组件

  • ref
// 父组件
class Content1 extends Component {
    sub = React.createRef();

    click = () => {
        this.sub.current.click();
    }
    render() {
        return (
            <div className="content">
              <Button onClick={this.click}>Btn1</Button>
              <Sub ref={this.sub}/>
            </div>
        )
    }
}
// 子组件
class Sub extends Component {
    click () {
        message.warning('hello Btn1!');
    }
    render() {
        return (
           <div style={{marginTop: '20px'}}>我是子组件</div>
        )
    }
}
  • onRef(传props属性,回调方法)
// 父组件
class Content2 extends Component {
    click = () => {
        this.sub.click();
    }
    onRef = (ref) => {
        this.sub = ref;
    }
    render() {
        return (
            <div className="content">
              <Button onClick={this.click}>Btn2</Button>
              <Sub onRef={this.onRef}/>
            </div>
        )
    }
}
// 子组件
class Sub extends Component {
    componentDidMount() {
        this.props.onRef(this);
    }
    click () {
        message.warning('hello Btn2!');
    }
    render() {
        return (
           <div style={{marginTop: '20px'}}>我是子组件</div>
        )
    }
}

2. 函数组件(useImperativeHandle

  • ref

forwardRef

// 父组件
const Content3 = () => {
    const ref = useRef(null);

    const click = () => {
        ref.current.click();
    }

    return (
        <div className="content">
            <Button onClick={click}>Btn3</Button>
            <Sub ref={ref}/>
        </div>
    )
}
// 子组件
const Sub = React.forwardRef((props, ref) => {
    const click = useCallback(() => {
        message.warning('hello Btn3!');
    }, [])
    useImperativeHandle(ref, () => ({
        click
    }), [click]);

    return (
        <div style={{marginTop: '20px'}}>我是子组件</div>
    )
})

  • 传props属性(可以不用forwardRef转发ref)
// 父组件
const Content4 = () => {
    const ref = useRef(null);

    const click = () => {
        ref.current.click();
    }

    return (
        <div className="content">
            <Button onClick={click}>Btn4</Button>
            <Sub t={ref}/>
        </div>
    )
}

// 子组件
const Sub = (props) => {
    const click = useCallback(() => {
        message.warning('hello Btn4!');
    }, [])
    useImperativeHandle(props.t, () => ({
        click
    }), [click]);

    return (
        <div style={{marginTop: '20px'}}>我是子组件</div>
    )
}