在表中添加和删除数据-React [英] Add and remove data to table - React
问题描述
我正在按React中的表格制作一个简单的名称和电子邮件列表.我想从服务器获取数据,然后可以动态添加或删除人员.这是我使用React的第一步,所以我遇到了问题.
I'm making a simple name and email list - by table in React. I want to fetch data from server, and next can add or remove persons dynamicly. This is my first steps with React, so I have a problem.
import React, { Component } from 'react';
import Form from "./Form";
class App extends Component {
constructor(props) {
super(props);
this.state = {
people: [],
};
this.addPerson = this.addPerson.bind(this);
}
addPerson(name, email) {
this.state.people.push({name: name, email: email});
}
componentDidMount() {
this.getPeople();
}
getPeople() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(response => this.setState({people: response}))
.catch(error => console.log(error));
}
render() {
return (
<div className='App'>
<Form/>
<table>
<thead>
<tr>
<th>LP</th>
<th>USER</th>
<th>EMAIL</th>
</tr>
</thead>
<tbody>
{this.state.people.map((person, index) => {
return (
<tr key={person.email}>
<th>{index + 1}</th>
<td>{person.name}</td>
<td>{person.email}</td>
</tr>
)
})}
</tbody>
</table>
</div>
)
}
}
export default App;
和表单组件:
import React, { Component } from 'react';
class Form extends Component {
constructor() {
super();
this.state = {
name: this.props.name,
email: this.props.email
};
this.handleChange = this.handleChange.bind(this);
this.addPerson = this.addPerson.bind(this);
/* this.formSubmit = this.formSubmit.bind(this); */
}
handleChange(e) {
this.setState({[e.target.id]: e.target.value})
}
addPerson(name, email) {
this.props.addPerson(name, email);
this.setState({name: '', email: ''});
}
render() {
return (
<form>
<input id='name' type='text' name={this.state.name} placeholder='Name...'/>
<input id='email' type='text' email={this.state.email} placeholder='Email...'/>
<input onClick={() => this.addPerson(this.state.name, this.state.email)} type='submit' value='submit'/>
</form>
)
}
}
export default Form;
现在我想可以向表中添加数据以进行表单提交,或者,如果我想要的话,可以删除表中的数据.我被困在这一刻...
And now i want to can add data to table for form submit, or if I want, delete data for table. I got stuck in this moment...
推荐答案
我将按照以下方式重写您的代码.
I'd rewrite your code as follows.
我将使 Form
组件成为 App
状态.我还添加了一个表单提交处理程序,该处理程序将在提交时获取输入值,然后从 App
调用 addPerson
方法以将名称添加到 people 根组件
App
维护的code>状态.
I will make Form
component as uncontrolled component. It means, the form inputs will maintain their own internal states when you change. There is no need to maintain two different sources of data. So I will rely on the parent component App
state. I also add a form submit handler which will get the inputs values on submit, and then call the addPerson
method from App
to add the names to the people
state maintained by root component App
.
我添加了 deletePerson
方法以从列表中删除人员.这是两个组件的样子.
I added the deletePerson
method to delete the people from the list. Here are the 2 components looks like.
deletePerson
方法在此依赖于以下事实:人员列表中的人员将带有 uniq 电子邮件.正如您还选择它作为 key
道具一样.但是您始终可以更改此标准,如果您了解当前的代码流程,这将很容易.
deletePerson
method here relies on the fact that people list will have person with uniq emails. As you also choose it as key
props. But you can always change this criterion which will be easy if you understand the current flow of the code.
import React, { Component } from "react";
import Form from "./Form";
class App extends Component {
constructor(props) {
super(props);
this.state = {
people: []
};
this.addPerson = this.addPerson.bind(this);
this.deletePerson = this.deletePerson.bind(this);
}
addPerson(name, email) {
this.setState(prevState => ({
people: [...prevState.people, { name, email }]
}));
}
componentDidMount() {
this.getPeople();
}
getPeople() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(response => this.setState({ people: response }))
.catch(error => console.log(error));
}
deletePerson(email) {
return () => {
this.setState(prevState => ({
people: prevState.people.filter(person => person.email !== email)
}));
};
}
render() {
console.log(this.state);
return (
<div className="App">
<Form addPerson={this.addPerson} />
<table>
<thead>
<tr>
<th>LP</th>
<th>USER</th>
<th>EMAIL</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{this.state.people.map((person, index) => {
return (
<tr key={person.email}>
<th>{index + 1}</th>
<td>{person.name}</td>
<td>{person.email}</td>
<td>
<button onClick={this.deletePerson(person.email)}>
Delete
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}
Form.js
import React, { Component } from "react";
class Form extends Component {
constructor() {
super();
this.formSubmit = this.formSubmit.bind(this);
}
formSubmit(event) {
event.preventDefault();
const form = event.target;
const email = form.elements["email"].value;
const name = form.elements["name"].value;
this.props.addPerson(name, email);
form.reset();
}
render() {
return (
<form onSubmit={this.formSubmit}>
<input
id="name"
type="text"
defaultValue=""
placeholder="Name..."
/>
<input
id="email"
type="text"
defaultValue=""
placeholder="Email..."
/>
<input type="submit" value="submit" />
</form>
);
}
}
export default Form;
请检查 Codesandbox 演示.
这篇关于在表中添加和删除数据-React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!