reactjs - 在反应js中将数据附加为表格
问题描述
我有一个应用程序,它从输入中获取日期并保存它,数据附加在下面,类似于待办事项列表。但是现在我在尝试显示数据时遇到问题,因为我想以特定顺序将其显示为表格行,但现在数据显示不正确,因为我想在名称下有名称,旧下有旧,删除按钮在删除文本下,编辑文本下的广告编辑按钮。
这个怎么做?
解决方案
您的代码中有一些问题。
- 您没有任何状态来跟踪添加的用户
- 在表单提交而不是更新数据时,您尝试使用提交的数据直接更新 DOM。这不是在反应中做事的正确方法。
import React, { useState, useEffect } from "react";
export default function App() {
const [user, setUser] = useState({
name: "",
old: ""
});
// A new state to keep track of the added users
const [users, setUsers] = useState([]);
const changeUser = e => {
const v = e.target.value;
setUser({
...user,
[e.target.name]: v
});
};
// On form submit, all you need to do is to update the users state
// Then render will take care of the rest
const submitForm = e => {
e.preventDefault();
setUsers([...users, user]);
};
// This is how in react we update the content
// Whenever, there is a change in state, this will get called and content will be updated
// Ps: It's being called in the render
const renderBody = () => {
const content = [];
users.map(item => {
content.push(
<tr>
<td>{item.name}</td>
<td>{item.old}</td>
<td>Delete btn</td>
<td>Edit btn</td>
</tr>
);
});
return content;
};
return (
<div className="to-do">
<form action="" onSubmit={submitForm}>
<label htmlFor="">
Name
<input
name="name"
onChange={changeUser}
value={user.name}
type="text"
/>
</label>
<label htmlFor="yes">
Old Yes
<input
id="yes"
name="old"
onChange={changeUser}
value="yes"
type="radio"
/>
</label>
<label htmlFor="no">
Old No
<input
id="no"
name="old"
onChange={changeUser}
value="no"
type="radio"
/>
</label>
<input value={user.old} type="submit" value="SUBMIT" />
</form>
<div className="res">
<table>
<tr>
<th>Name</th>
<th>OLD</th>
<th>DELETE</th>
<th>Edit</th>
</tr>
<tr id="res" />
{renderBody()}
</table>
</div>
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
所以你需要什么
- 用户状态以跟踪添加的用户
- 在表单提交时,更新用户状态的触发器
- 一个循环,遍历用户数组并返回包含内容的表行