如何让React父组件访问不带表单的子状态(使用沙箱)?

时间:2019-04-09 16:33:37

标签: javascript reactjs react-hooks

我目前正在寻找一种从父组件访问子state的方法,该子组件将处理整个页面的API调用。

实际问题如下:

Parent是父组件,它将呈现两个Child组件。

每个Child都有其应负责的状态。

“提交按钮的种类”将具有“提交动作的种类”(所有引用都是因为这不是表格),并且应该触发该函数以提供对子状态的访问。有没有一种方法(某些React功能)可以在不使用<form>的情况下,也可以不创建中间的父组件来保存所有状态的方法呢?我希望每个孩子都应对自己的状态负责。

Code Sandbox with example of the code below

import React, { useState, useRef } from "react";

function ChildOne() {
  const [childOneState, setChildOneState] = useState(false);

  return (
    <React.Fragment>
      <h3>Child One</h3>
      <p>My state is: {childOneState.toString()}</p>
      <button onClick={() => setChildOneState(true)}>Change my state</button>
    </React.Fragment>
  );
}

function ChildTwo() {
  const [childTwoState, setChildTwoState] = useState(false);

  return (
    <React.Fragment>
      <h3>Child Two</h3>
      <p>My state is: {childTwoState.toString()}</p>
      <button onClick={() => setChildTwoState(true)}>Change my state</button>
    </React.Fragment>
  );
}

function Button(props) {
  return (
    <button onClick={props.kindOfSubmitAction}>Kind of Submit Button</button>
  );
}

function Parent() {
  const childOneState = useRef("i have no idea");
  const childTwoState = useRef("ihave no idea");

  function kindOfSubmitAction() {
    console.log("This is the kindOfSubmit function!");
    // This function would somehow get
    // access to the children state and store them into the refs
    return;
  }

  return (
    <React.Fragment>
      <h1>Iam Parent</h1>
      <div>
        <b>Child one state is: </b>
        {childOneState.current}
      </div>
      <div>
        <b>Child two state is: </b>
        {childTwoState.current}{" "}
      </div>

      <Button kindOfSubmitAction={kindOfSubmitAction} />

      <ChildOne />
      <ChildTwo />

    </React.Fragment>
  );
}

export default Parent;

1 个答案:

答案 0 :(得分:2)

当几个组件需要访问同一数据时,就该Lifting State Up了。