【问题标题】:React: render form with set of fields depended from selected valueReact:使用取决于所选值的字段集呈现表单
【发布时间】:2020-09-24 16:38:15
【问题描述】:

这里是例子:https://codesandbox.io/s/priceless-brown-ib4w6

import React from "react";
import "./styles.css";

const MyForm = (props) => {
  return React.Children.map(props.children, (element) => {
    return element && <div>Addon: {element}</div>;
  });
};

const MyComponentA = (props) => {
  return (
    <>
      <span>Component A-1</span>
      <span>Component A-2</span>
    </>
  );
};

const MyComponentB = (props) => {
  return (
    <>
      <span>Component B-1</span>
      <span>Component B-2</span>
    </>
  );
};

export default function App() {
  const [type, setType] = React.useState("a");

  const handleChange = (e) => {
    setType(e.target.value);
  };
  return (
    <div className="App">
      <MyForm>
        <select onChange={handleChange}>
          <option name="A" value="a">
            A
          </option>
          <option name="B" value="b">
            B
          </option>
        </select>
        <span>Text1</span>
        <span>Text2</span>
        {type === "a" && <MyComponentA />}
        {type === "b" && <MyComponentB />}
      </MyForm>
    </div>
  );
}

有一种形式会在其每个子项上添加一些包装器。并且有一个选择字段可以修改呈现的表单字段的子集。 MyComponents 旨在对这些更改的部分进行分组。但这会破坏作为 MyForm 一部分的最终 Mycomponents 子级。考虑 MyForm 是第三方代码,无法更改。如何正确组织这样的代码,达到正确的渲染,同时保持字段组?

目标是:

Addon: Text1
Addon: Text2
Addon: Component A-1
Addon: Component A-2

而不是:

Addon: Text1
Addon: Text2
Addon: Component A-1Component A-2

【问题讨论】:

    标签: javascript html reactjs forms


    【解决方案1】:

    问题是 MyForm 只是循环通过它的直接子元素并将它们包装在 AddOn div 中。在您的情况下,直接子级是 MyComponentA 和 MyComponentB。它们的子元素不是 MyForm 的直接子元素,因此整个组件都包含在 AddOn div 中。

    您可以将它们从组件更改为像这样的简单元素数组

    改变

    const MyComponentA = (props) => {
       return (
        <>
          <span>Component A-1</span>
          <span>Component A-2</span>
       </>
      );
    };
    

    const MyComponentB = [<span>Component B-1</span>, <span>Component B-2</span>];
    

    然后在应用中渲染它们时,只需传入该值(而不是作为反应组件)

    改变

     {type === "a" && <MyComponentA />}
     {type === "b" && <MyComponentB />}
    

     {type === "a" && MyComponentA}
     {type === "b" && MyComponentB}
    

    希望对你有帮助

    【讨论】:

    • 谢谢。我考虑了这个明显的解决方案,但我认为这里有更多更好和更常见的方法。我的意思是当部分表单字段从下拉选择器中更改依赖项时的实现。
    猜你喜欢
    • 2012-05-23
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多