【发布时间】:2022-01-15 11:24:49
【问题描述】:
我想将问题数组映射到表格行。在为任何行中设置上传图像的预览时,它总是在第一个渲染。理想情况下,对于每个有问题的对象数组,一旦输入文件,它的预览将显示在下一个 img 标签中。你能告诉我如何纠正它吗?
const [questions, setQuestions] = useState([]); // it will contain an array of objects
// like [{quesID, ques, options, media}, {quesID, ques, options, media} ]
<table aria-label="simple table">
<thead>
<tr>
<td>Question</td>
<td>Options</td>
<td align="center">
Grade
</td>
<td align="center">
Level
</td>
<td align="center">
Subject
</td>
<td align="center">
Topic 1
</td>
<td align="center">
Topic 2
</td>
<td align="center">
Topic 3
</td>
<td align="center">
Upload image
</td>
<td align="center">
Preview image
</td>
</tr>
</thead>
<tbody>
{questions.map((row) => (
<tr key={row.id}>
<td
style={{ border: "1px solid black" }}
component="th"
scope="row"
>
<TextField
margin="dense"
id="editQues"
variant="filled"
multiline
sx={{
width: 300,
color: "success.main",
}}
maxRows={4}
defaultValue={row.ques}
onChange={(e) => {
row.ques = e.target.value;
console.log(row.ques);
console.log(e.target.value);
}}
/>
</td>
<td
style={{ border: "1px solid black" }}
component="th"
scope="row"
>
<TextField
margin="dense"
id="editOpt"
variant="filled"
multiline
sx={{
width: 200,
color: "success.main",
}}
maxRows={4}
defaultValue={row.options.join(", ")}
onChange={(e) => {
row.options = e.target.value.split(", ");
console.log(row.options);
console.log(e.target.value);
console.log("updated questions is", questions);
}}
/>
</td>
<td
style={{ border: "1px solid black" }}
align="center"
>
{row.grade.join(",")}
</td>
<td
style={{ border: "1px solid black" }}
align="center"
>
{row.level}
</td>
<td
style={{ border: "1px solid black" }}
align="center"
>
{row.subject}
</td>
<td
style={{ border: "1px solid black" }}
align="center"
>
{row.topic}
</td>
<td
style={{ border: "1px solid black" }}
align="center"
>
{row.subTopic ? row.subTopic : ""}
</td>
<td
style={{ border: "1px solid black" }}
align="center"
>
{row.subSubTopic ? row.subSubTopic : ""}
</td>
<td style={{ border: "1px solid black" }}>
<input
type="file"
id="uploadMedia"
name="uploadMedia"
accept="image/*, video/* "
onChange={(event) => {
const file = event.target.files[0];
if (file) {
row.file = file;
var output = document.getElementById("blah");
output.src = URL.createObjectURL(
event.target.files[0]
);
output.onload = function () {
// URL.revokeObjectURL(output.src); // free memory
};
} else {
row.file = null;
}
console.log("media", row.file);
}}
/>
</td>
<td
style={{ border: "1px solid black" }}
align="center"
scope="row"
>
<img
id="blah"
src="#"
alt="your image"
width="100"
height="100"
/>
</td>
</tr>
))}
</tbody>
</table>
【问题讨论】:
-
我认为这里没有足够的信息来回答这个问题,但我注意到你正在变异
row(row.ques = e.target.value、row.file = file等),这看起来很可疑。您通常应该使用状态设置器来更新内容。 -
您好,感谢您的评论。有没有其他方法可以选择相关行的 img 标签,如图所示?从任何输入中选择图像现在仅在第一个 img 中更新图像。像这里我正在使用 var output document.getElementById("blah");它总是给出第一行图像,但它必须为每一行映射图像。
标签: javascript reactjs image html-table