我正在制作一个简单的姓名和电子邮件列表 - 在 React 中按表格。我想从服务器获取数据,然后可以动态添加或删除人员。这是我使用 React 的第一步,所以我遇到了问题。
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;
现在我想可以将数据添加到表格以提交表格,或者如果我愿意,可以删除表格的数据。我被困在这一刻...