react 父组件获取子组件的状态(调用子组件的方法)

882 阅读1分钟

前言

在React中,我们经常在子组件中调用父组件的方法,一般用props回调即可。但是有时候也需要在父组件中调用子组件的方法,通过这种方法实现高内聚。有多种方法,请按需服用。

子组件为类组件

React.createRef()

<body>
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

    <div id="app"></div>

    <script type="text/babel">
    
      //子组件
      class Child extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            name: "我是子组件的name",
          };
        }
        render() {
          return <h2>child</h2>;
        }
      }
      
      
      //父组件
      class App extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            name: "",
          };
          this.childRef = React.createRef();
        }

        btnClick() {
          console.log(this.childRef.current.state.name);
          this.setState({
            name: this.childRef.current.state.name,
          });
        }

        render() {
          return (
            <div>
              <h2>name : {this.state.name}</h2>
              <Child ref={this.childRef} />
              <button onClick={() => this.btnClick()}>获取</button>
            </div>
          );
        }
      }

      ReactDOM.render(<App />, document.getElementById("app"));
    </script>
  </body>

image.png

点击获取拿到子组件的state

函数组件、Hook组件

useImperativeHandle

forwardRef

<script type="text/babel">
       //子组件
      const Child = React.forwardRef((props, ref) => {
        const [name, setName] = React.useState("ws");
        const childFunc = () => {
          console.log("我是子组件的方法");
        };
        React.useImperativeHandle(ref, () => ({
          childFunc,
          name,
        }));

        return (
          <div>
            <h2>我是子组件</h2>
            <button onClick={()=> setName('wujiali')}> 修改name</button>
          </div>
        );
      });
      
      
      // 父组件
      class App extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            name: "",
          };
          this.childRef = React.createRef();
        }

        btnClick() {
          console.log(this.childRef);
          this.setState({
            name: this.childRef.current.name,
          });
        }

        render() {
          return (
            <div>
              <h2>父组件中获取到的子组件的 name : {this.state.name}</h2>
              <Child ref={this.childRef} />
              <button onClick={() => this.btnClick()}>获取</button>
            </div>
          );
        }
      }

      ReactDOM.render(<App />, document.getElementById("app"));
    </script>

image.png

image.png