【问题标题】:Keep data in inputs using ant design使用 ant design 将数据保存在输入中
【发布时间】:2020-11-06 08:09:04
【问题描述】:

我创建了一个包含 2 个步骤的应用程序。在每一步,用户都应该在输入中添加一些数据。 单击按钮2 后,用户更改步骤。我想创建一个场景:

  1. 用户从第一步填写表格,然后点击按钮2
  2. 当用户点击按钮1 时,应该会出现第一个表单,其中包含之前添加的数据。

const [state, seState] = useState(1);

  const one = () => {
    seState(1);
  };

  const two = () => {
    seState(2);
  };
  return (
    <div>
      {state === 1 ? <Form1 /> : <Form2 />}
      <button onClick={one}>1</button>
      <button onClick={two}>2</button>
    </div>
  );
};

演示:https://codesandbox.io/s/basic-usage-antd480-forked-kdyyn?file=/index.js:252-615
问题:ant 是否设计了这个内置功能?如何保留每个步骤的数据,以及用户何时切换步骤时数据应该在输入中?

【问题讨论】:

  • 您基本上需要在两个表单之间共享状态,因此您可以将这些状态存储在父组件中。您可以从文档中了解更多信息:reactjs.org/docs/lifting-state-up.html

标签: reactjs antd


【解决方案1】:

要保留数据,无论是否蚂蚁,您都需要做出选择。首先,您可以将所有表单保留在 DOM 中并使用 CSS 隐藏它们(sandbox):

  const [state, seState] = useState(1);

  const one = () => {
    seState(1);
  };

  const two = () => {
    seState(2);
  };
  return (
    <div>
      <div style={state === 1 ? { display: "block" } : { display: "none" }}>
        <Form1 />
      </div>
      <div style={state === 2 ? { display: "block" } : { display: "none" }}>
        <Form2 />
      </div>
      <button onClick={one}>1</button>
      <button onClick={two}>2</button>
    </div>
  );

其次,您可以选择每次执行 setState 时重新填写表单值,方法是将数据保存在共享存储中,例如 redux 或 userReducer。对于不需要太多逻辑且没有大型 DOM 的简单表单,我选择了第一种方法。在动态和复杂的数据场景中,第二种方法可能是更好的选择。

【讨论】:

猜你喜欢
  • 2021-04-27
  • 1970-01-01
  • 2019-10-22
  • 2021-01-31
  • 1970-01-01
  • 2020-03-15
  • 2021-04-18
  • 2020-07-11
  • 1970-01-01
相关资源
最近更新 更多