【发布时间】:2022-01-10 22:55:14
【问题描述】:
对于我的示例项目,我正在 ReactJs 中尝试一些东西,我将在其中获取多个值并将它们拆分为两个或更多对象。我对 reactjs 没有太多经验,所以如果您有任何示例或网站可以帮助我提高我的 reactjs 技能,或者您可以给我任何建议,我将不胜感激。如果您有任何不明白或需要澄清的地方,请在下方留言。
当我提交时,它只显示蓝色和中等值,这是有道理的,因为我的代码不允许输入多个值。有没有办法解决或改进它?我想在每个输入的两个多个输入之后对其进行测试,因此我想构建某种类型的动态多个输入,它不仅可以管理两个相同的类别值,如红色和蓝色,还可以处理相同颜色类别的三个输入。
代码
import React, { useState } from "react";
import { Button, Form, Grid } from "semantic-ui-react";
function Sample() {
const [attributes, setAttributes] = useState([]);
const [color, setColor] = useState("");
const [size, setSize] = useState("");
const onSubmit = () => {
setAttributes([
...attributes,
{
id: new Date().getTime() + attributes.length,
color: color,
size: size,
},
]);
setColor("");
setSize("");
};
console.log(attributes);
return (
<>
<Form onSubmit={onSubmit}>
<h2>Create a Child Attributes:</h2>
<Form.Field>
<Grid columns={2}>
<Grid.Row>
<Grid.Column>
<Form.Input
placeholder="Please Enter Color"
name="color"
label="Color: "
onChange={(event) => {
setColor(event.target.value);
}}
/>
<Form.Input
placeholder="Please Enter Color"
name="color"
label="Color: "
onChange={(event) => {
setColor(event.target.value);
}}
/>
</Grid.Column>
<Grid.Column>
<Form.Input
placeholder="Please Enter Size"
name="size"
label="Size: "
onChange={(event) => {
setSize(event.target.value);
}}
/>
<Form.Input
placeholder="Please Enter Size"
name="size"
label="Size: "
onChange={(event) => {
setSize(event.target.value);
}}
/>
</Grid.Column>
</Grid.Row>
</Grid>
<br />
<Button type="submit" color="teal">
Submit
</Button>
</Form.Field>
</Form>
<table className="ui celled sortable table">
<thead>
<tr>
<th>ID</th>
<th>Color</th>
<th>Size</th>
</tr>
</thead>
<tbody>
{attributes.map(({ id, color, size }) => (
<tr key={id}>
<td>{id}</td>
<td>{color}</td>
<td>{size}</td>
</tr>
))}
</tbody>
</table>
</>
);
}
export default Sample;
代码沙箱 => https://codesandbox.io/s/affectionate-mayer-1ecqw?file=/src/App.js
【问题讨论】:
-
点击提交时您期望发生什么?向表中添加新条目或将值添加到具有逗号分隔的多个值的同一行?
-
嗨,谢谢你的评论,当我点击提交时我想要它向表中添加新条目,而不是用逗号分隔的一行
标签: javascript arrays reactjs json object