react函数父组件获取类子组件state

父组件

import {  Button } from 'antd';
import Child from './Child';
function Parent() {
    let childRef = null;
    const getData = () => {
        console.log(childRef.state.msg)
      }
    return (
        

我是父组件

(childRef = r)}>
) } export default Parent

 父组件中绑定ref和class组件有所不同,通过ref={(r) => (childRef = r)}绑定

子组件 

import React from "react";

class child extends React.Component {
    constructor(props) {
        super(props);
        this.state = { msg: '我是子组件' };
    }
    render() {
        return (
            

子组件

) } } export default child;

 最终效果,点击按钮获取子组件的state

react函数父组件获取类子组件state_第1张图片

 

你可能感兴趣的:(react.js,javascript,前端)