如何让 React parent 组件访问 children 状态而无需表单(使用 Sandbox)?

How to give React parent component access to children state without form (with Sandbox)?

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

实际问题如下:

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

每个 Child 都有一个它负责的状态。

"Kind of Submit Button" 将有一个 "Kind of Submmit Action"(这全部被引用是因为这不是一个表单)并且应该触发函数以提供对 children 状态的访问。有没有一种方法(某些 React 功能)可以在不使用 <form> 或不创建中间 parent 组件来保存所有状态的情况下执行此操作?我希望每个 children 对自己的状态负责。

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;

当多个组件需要访问相同的数据时,是时候 Lifting State Up