【问题标题】:What is the best way to add additional input field on a button click?在单击按钮时添加其他输入字段的最佳方法是什么?
【发布时间】:2021-01-02 08:47:33
【问题描述】:

我想知道从按钮上的 onClick() 添加附加输入字段的标准方法是什么。 一个场景可能是在点击时添加一个待办事项列表项字段。

我的方法是使用一个状态数组来存储实际组件并连接数组。

const[ComponentList, setComponentList] = useState([<Component id={1}/>]);

然后……

function addAnotherQuestion() {
    setComponentList(ComponentList.concat(generateComponent(currentID)));
 }

有人告诉我这是一个非常糟糕的主意,并且由于过时状态(我这样做了,然后我通过直接从子组件写入 Redux 存储来解决),我最终会得到混乱的输入。这不是一个理想的解决方案,所以我想知道这样做的标准方法是什么?

【问题讨论】:

    标签: reactjs input react-redux


    【解决方案1】:

    我只会像这样将输入数据存储在数组中:

    const [inputs, setInputs] = useState(["some_id_1", "some_id_2", "some_id_3"]);
    
    function addAnotherQuestion() {
        setInputs(inputs.concat(currentID));
    }
    

    然后分别渲染:

    <>
     { inputs.map((id) => <Component key={id} id={id}/>) }
    </>
    

    【讨论】:

    • 我将我的代码重构为与此类似。效果很好。
    【解决方案2】:

    保留一个 ID 数组而不是组件怎么样?

    const[ComponentListIds, setComponentListIds] = useState([1]);
    

    为什么需要生成组件?您可能应该做的是生成新的 ID。然后在组件的渲染部分渲染组件:

    render(
    ...
    ComponentListIds.map(id=> <Component key={id} id={id}>)
    ...
    )
    

    【讨论】:

    • 组件是一个输入域,当用户点击一个按钮时生成。想去做应用程序。用户点击“添加待办事项”按钮,就会添加一个新的待办事项输入组件。
    猜你喜欢
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多