首页 > 解决方案 > 如何让 React 父组件在没有表单的情况下访问子状态(使用沙盒)?

问题描述

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

实际问题如下:

Parent是将渲染两个组件的父Child组件。

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

“Kind of Submit Button”将有一个“Kind of Submmit Action”(所有这些都被引用,因为这不是一个表单)并且应该触发该函数以提供对子状态的访问。有没有办法(一些 React 特性)在不使用<form>或不创建中间父组件来保存所有状态的情况下做到这一点?我希望每个孩子都对自己的状态负责。

带有以下代码示例的代码沙箱

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;

标签: javascriptreactjsreact-hooks

解决方案


当多个组件需要访问相同的数据时,就该提升状态了


推荐阅读