我想知道在按钮上从onClick((添加额外输入字段的标准方法是什么一种场景可能是在单击时添加一个Todo列表项字段
我的方法是使用一个状态数组来存储实际组件并连接数组。
const[ComponentList, setComponentList] = useState([<Component id={1}/>]);
然后。。。
function addAnotherQuestion() {
setComponentList(ComponentList.concat(generateComponent(currentID)));
}
有人告诉我,这是一个非常糟糕的主意,我会因为过时的状态而导致输入混乱(我做到了,然后我通过直接从子组件写入Redux存储来解决这个问题(。这不是一个理想的解决方案,所以我想知道做这件事的标准方法是什么?
我只将输入数据存储在数组中,如下所示:
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}/>) }
</>
保留一个Id数组而不是组件怎么样?
const[ComponentListIds, setComponentListIds] = useState([1]);
为什么需要生成组件?您可能应该做的是生成新的Id。然后使用在组件的渲染部分中渲染组件
render(
...
ComponentListIds.map(id=> <Component key={id} id={id}>)
...
)