react 事件处理
在使用React渲染RESTful服务后,我们创建了简单的UI,用于渲染从RESTful服务获取的员工列表。 作为本文的一部分,我们将扩展同一应用程序以支持添加和删除员工操作。
我们将通过添加/删除员工操作来更新react-app后端api,并修改现有的get employee方法以返回员工列表,方法如下:
步骤1.定义由@PostMapping(“ / employee / add”)标记的addEmployee方法,该方法将在类级别的员工列表中添加员工:
@PostMapping("/employee/add")
public List<Employee> addEmployee(final @RequestBody Employee employee) {System.out.println("Adding employee with name : " + employee.getName());if(employee.getName() != null && employee.getName().length() > 0)employeeList.add(new Employee(employeeList.size(), employee.getName(), "IT"));return employeeList;
}
步骤2.定义由@PostMapping(“ / employee / delete”)标记的deleteEmployee方法, 该方法将从与雇员姓名匹配的类级别雇员列表中删除雇员,如下所示:
@PostMapping("/employee/delete")
public List<Employee> deleteEmployee(final @RequestBody Employee employee) {System.out.println("Deleting employee with name : " + employee.getName());final Optional<Employee> optional = employeeList.stream().filter(e -> e.getName().equalsIgnoreCase(employee.getName())).findAny();if(optional.isPresent()){employeeList.remove(optional.get());}return employeeList;
}
最终, ReactAppApplication.java应该看起来像:
@SpringBootApplication
@RestController
public class ReactAppApplication {final List<Employee> employeeList = new ArrayList<>();public static void main(String[] args) {SpringApplication.run(ReactAppApplication.class, args);}@GetMapping("/employee/get")public List<Employee> get() {return employeeList;}@PostMapping("/employee/add")public List<Employee> add(final @RequestBody Employee employee) {System.out.println("Adding employee with name : " + employee.getName());if(employee.getName() != null && employee.getName().length() > 0)employeeList.add(new Employee(employeeList.size(), employee.getName(), "IT"));return employeeList;}@PostMapping("/employee/delete")public List<Employee> delete(final @RequestBody Employee employee) {System.out.println("Deleting employee with name : " + employee.getName());final Optional<Employee> optional = employeeList.stream().filter(e -> e.getName().equalsIgnoreCase(employee.getName())).findAny();if(optional.isPresent()){employeeList.remove(optional.get());}return employeeList;}
}
步骤3:在ReactApp组件中定义addEmployee方法/处理程序,该方法以员工名称作为POST调用的负载,作为我们刚刚在控制器中定义的addEmployee方法的有效负载,如下所示:
/Users/ArpitAggarwal/react-app/app/components/react-app.jsx
addEmployee(employeeName){let _this = this;this.Axios.post('/add', {name: employeeName}).then(function (response) {console.log(response);_this.setState({employees: response.data});}).catch(function (error) {console.log(error);});
}
步骤4:在ReactApp组件的构造函数中绑定addEmployee处理程序:
constructor(props) {super(props);this.state = {employees: []};this.addEmployee = this.addEmployee.bind(this);this.Axios = axios.create({baseURL: "/employee",headers: {'content-type': 'application/json', 'creds':'user'}});
}
步骤5:渲染子组件– AddEmployee作为ReactApp组件渲染方法的一部分,将addEmployee处理程序作为react 道具传递,以建立父子通信:
render() {return (<div><AddEmployee addEmployee={this.addEmployee}/><EmployeeList employees={this.state.employees}/></div>)
}
步骤6:在组件目录中创建add-employee组件,如下所示:
cd react-app/app/components/
touch add-employee.jsx
并复制以下内容:
react-app / app / components / add-employee.jsx
import React, { Component, PropTypes } from 'react'export default class AddEmployee extends React.Component {render(){return (<div><input type = 'text' ref = 'input' /><button onClick = {(e) => this.handleClick(e)}>Add Employee</button></div>)}handleClick(e) {const node = this.refs.inputconst text = node.value.trim()console.log(text);this.props.addEmployee(text)node.value = ''}
}
如上所定义的handleClick(e)中函数调用上添加员工按钮点击这将进一步调用使用的道具 ReactApp定义addEmployee处理程序。
完成所有这些操作后,我们的react-app可以执行添加员工操作。 接下来,我们将进一步扩展该功能以支持删除员工的操作。
步骤7:定义deleteEmployee处理程序,并以与addEmployee处理程序相同的方式绑定到ReactApp中:
/Users/ArpitAggarwal/react-app/app/components/react-app.jsx
constructor(props) {super(props);this.state = {employees: []};this.addEmployee = this.addEmployee.bind(this);this.deleteEmployee = this.deleteEmployee.bind(this);this.Axios = axios.create({baseURL: "/employee",headers: {'content-type': 'application/json', 'creds':'user'}});
}deleteEmployee(employeeName){let _this = this;this.Axios.post('/delete', {name: employeeName}).then(function (response) {_this.setState({employees: response.data});console.log(response);}).catch(function (error) {console.log(error);});
}
步骤8:将 deleteEmployee处理函数传递给EmployeeList组件,该组件将进一步将其传递给它的子容器:
render() {return (<div><AddEmployee addEmployee={this.addEmployee}/><EmployeeList employees={this.state.employees} deleteEmployee={this.deleteEmployee}/></div>)}
最终, ReactApp组件应如下所示:
'use strict';
const React = require('react');
var axios = require('axios');import EmployeeList from './employee-list.jsx'
import AddEmployee from './add-employee.jsx'export default class ReactApp extends React.Component {constructor(props) {super(props);this.state = {employees: []};this.addEmployee = this.addEmployee.bind(this);this.deleteEmployee = this.deleteEmployee.bind(this);this.Axios = axios.create({baseURL: "/employee",headers: {'content-type': 'application/json', 'creds':'user'}});}componentDidMount() {let _this = this;this.Axios.get('/get').then(function (response) {console.log(response);_this.setState({employees: response.data});}).catch(function (error) {console.log(error);});}addEmployee(employeeName){let _this = this;this.Axios.post('/add', {name: employeeName}).then(function (response) {console.log(response);_this.setState({employees: response.data});}).catch(function (error) {console.log(error);});}deleteEmployee(employeeName){let _this = this;this.Axios.post('/delete', {name: employeeName}).then(function (response) {_this.setState({employees: response.data});console.log(response);}).catch(function (error) {console.log(error);});}render() {return (<div><AddEmployee addEmployee={this.addEmployee}/><EmployeeList employees={this.state.employees} deleteEmployee={this.deleteEmployee}/></div>)}
}
步骤9:更新EmployeeList组件以将deleteEmployee处理程序传递给它的子组件– Employee,方法是将其与render方法中的更改一起导入,以具有Delete列:
const React = require('react');
import Employee from './employee.jsx'export default class EmployeeList extends React.Component{render() {var employees = this.props.employees.map((employee, i) =><Employee key={i} employee={employee} deleteEmployee={() => this.props.deleteEmployee(employee.name)}/>);return (<table><tbody><tr><th>ID</th><th>Name</th><th>Department</th><th>Delete</th></tr>{employees}</tbody></table>)}
}
步骤10:更新Employee组件以进行渲染– DeleteEmployee组件通过deleteEmployee处理程序:
const React = require('react');
import DeleteEmployee from './delete-employee.jsx'export default class Employee extends React.Component{render() {return (<tr><td>{this.props.employee.id}</td><td>{this.props.employee.name}</td><td>{this.props.employee.department}</td><td><DeleteEmployee deleteEmployee={this.props.deleteEmployee}/></td></tr>)}
}
步骤11:在组件目录内创建delete-employee组件:
cd react-app/app/components/
touch delete-employee.jsx
并复制以下内容:
react-app / app / components / delete-employee.jsx
import React, { Component, PropTypes } from 'react'export default class DeleteEmployee extends React.Component {render(){return (<button onClick = {(employeeName) => this.handleDelete(employeeName)}>Delete</button>)}handleDelete(employeeName) {this.props.deleteEmployee(employeeName);}
}
上面定义的handleDelete(employeeName)函数在Delete按钮单击时调用,这将进一步使用props调用ReactApp中定义的deleteEmployee处理程序。
一切就绪后,目录结构应如下所示:
现在,重新运行该应用程序并访问http:// localhost:8080 ,一旦您添加了几名员工,它应如下图所示。
完整的源代码托管在github上 。
翻译自: https://www.javacodegeeks.com/2017/05/handling-events-react.html
react 事件处理