React 中从子组件获取组件值

问题描述 投票:0回答:1

我已经为表单创建了下拉/查找组件,每个组件都作为单独的文件存储在组件文件夹下。目前,每个组件中的项目列表都是从组件内的数组提供的以进行测试,并且最终将来自 API 调用。当用户从下拉列表中选择一个选项时,我对每个组件进行编码以更新使用状态。然后,我创建了一个表单,导入了子组件并添加了一个提交按钮。我正在努力的地方是获取与提交按钮一起使用的列表框的值。我想我需要使用状态,但我对 React 的理解(仍然非常新,这是我的第一个项目)是状态从父级流向子级,而不是相反。我已包含我的表单和子组件之一。有人可以向我展示/解释我需要做什么吗?

家长:

`import "bootswatch/dist/sandstone/bootstrap.css";
import SelectGrowers from "./Components/SelectGrowers";
import SelectStacks from "./Components/SelectStacks";
import SelectCustomers from "./Components/SelectCustomers";
import SelectCarriers from "./Components/SelectCarriers";

function AddPOForm() {
  return (
    <>
      <form className="form-group">
        <div className="container">
          <div className="row">
            <div id="growers" className="col-sm-4">
              <SelectGrowers />
            </div>

            <div className="col-sm-4">
              <SelectStacks />
            </div>
          </div>


          <div className="row">
            <div className="col-sm-4">
              <SelectCustomers />
            </div>

            <div className="col-sm-4">
              <SelectCarriers />
            </div>
          </div>
        </div>
        <input type="Submit" />
      </form>
    </>
  );
}

export default AddPOForm;`

** 子组件:**

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

interface Props {
  onSelectItem: (item: string) => void;
}

export default function SelectGrowers() {
  let growers = [
    { id: 1, value: "Grower A" },
    { id: 2, value: "Grower B" },
    { id: 3, value: "Grower C" },
  ];
  let [grower, setGrower] = useState();

  let handlGrowerChange = () => {
    setGrower(grower);
  };

  return (
    <div className="form-group">
      <label htmlFor="growerList" className="form-label mt-4">
        Grower
      </label>
      <select
        onChange={() => handlGrowerChange}
        name="growerList"
        className="form-select"
      >
        <option>Please Select a Grower</option>
        {growers.map((grower) => (
          <option key={grower.id}>
            {grower.id} - {grower.value}
          </option>
        ))}
      </select>
    </div>
  );
}`
reactjs forms react-hooks components
1个回答
0
投票

您走在正确的道路上。但是,如果您计划使用父组件中的数据,则需要在其中保留状态。因此,将此行

let [grower, setGrower] = useState();
移动到父文件中。现在,无论选择什么新值,都使用传递给子组件的回调来更新父组件中的状态。

父组件:

let [grower, setGrower] = useState();

let handlGrowerChange = (grower) => {
  setGrower(grower);
};

... 

<SelectGrowers onSelectItem={handleGrowerChange} />

最终,如果您需要控制选择,您也可以将状态值传递给您的子组件。

© www.soinside.com 2019 - 2024. All rights reserved.