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條經驗 獲得超13個贊
您需要更改狀態以在某處包含文本字符串數組,而不僅僅是單個字符串。然后使用正在迭代的元素的索引來確定要設置什么值以及要在更改時更改什么索引。
我認為最優雅的解決方案是更改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>
));
添加回答
舉報