3 回答

TA贡献1895条经验 获得超7个赞
您需要使用数组而不是字符串作为文本状态,因为每个评论都有状态
const [text, setText] = useState(new Array(comments.length));
comments.map((c,i) => (
<Row key={c._id}>
<Form
onSubmit={(e) => {
e.preventDefault();
addComment(comment._id, { text });
setText(new Array(comments.length));
}}
>
<InputGroup className="mb-3">
<FormControl
placeholder="add a comment"
aria-label="add a comment"
aria-describedby="inputGroup-sizing-default"
value={text[i]}
onChange={(e) => {
const newText = [...text];
newText[i] = e.target.value;
setText(newText);
}}
/>
</InputGroup>
</Form>
</Row>
));
由于状态是数组,现在您需要将值设置为text[i],当您更改状态时,您需要更改元素上的i文本

TA贡献1842条经验 获得超12个赞
您需要更改状态以在某处包含文本字符串数组,而不仅仅是单个字符串。然后使用正在迭代的元素的索引来确定要设置什么值以及要在更改时更改什么索引。
我认为最优雅的解决方案是更改comments对象以包含text属性,例如:
{
_id: 'somekey',
text: ''
// ...
}
然后映射它们:
const setCommentText = (text, i) => setComments(
comments.map(
(comment, i) => comment !== i ? comment : { ...comment, text }
)
);
comments.map((c, i) => (
<Row key={c._id}>
<Form onSubmit={e => {
e.preventDefault();
addComment(comment._id, {c.text});
setCommentText('', i);
}}>
<InputGroup className="mb-3" >
<FormControl
placeholder="add a comment"
aria-label="add a comment"
aria-describedby="inputGroup-sizing-default"
value={c.text}
onChange={e => setCommentText(e.target.value, i)}
/>
</InputGroup>
</Form>
</Row>
));

TA贡献1853条经验 获得超6个赞
试试这个方法
const [inputValues, setInputValues] = useState([]);
const updateValue = (value, index) => {
const newInputValues = [... inputValues];
newInputValues[index] = value
setInputValues(newInputValues);
}
comments.map((c, index) => (
<Row key={c._id}>
....
<InputGroup className="mb-3">
<FormControl
.......
value={inputValues[index] || ""}
onChange={(e) => setInputValues(e.target.value)}
/>
</InputGroup>
</Form>
</Row>
));
添加回答
举报