react 事件处理_在React中处理事件
react 事件處理
在使用React渲染RESTful服務(wù)后,我們創(chuàng)建了簡(jiǎn)單的UI,用于渲染從RESTful服務(wù)獲取的員工列表。 作為本文的一部分,我們將擴(kuò)展同一應(yīng)用程序以支持添加和刪除員工操作。
我們將通過(guò)添加/刪除員工操作來(lái)更新react-app后端api,并修改現(xiàn)有的get employee方法以返回員工列表,方法如下:
步驟1.定義由@PostMapping(“ / employee / add”)標(biāo)記的addEmployee方法,該方法將在類級(jí)別的員工列表中添加員工:
@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”)標(biāo)記的deleteEmployee方法, 該方法將從與雇員姓名匹配的類級(jí)別雇員列表中刪除雇員,如下所示:
@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應(yīng)該看起來(lái)像:
@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調(diào)用的負(fù)載,作為我們剛剛在控制器中定義的addEmployee方法的有效負(fù)載,如下所示:
/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組件的構(gòu)造函數(shù)中綁定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:在組件目錄中創(chuàng)建add-employee組件,如下所示:
cd react-app/app/components/ touch add-employee.jsx并復(fù)制以下內(nèi)容:
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)中函數(shù)調(diào)用上添加員工按鈕點(diǎn)擊這將進(jìn)一步調(diào)用使用的道具 ReactApp定義addEmployee處理程序。
完成所有這些操作后,我們的react-app可以執(zhí)行添加員工操作。 接下來(lái),我們將進(jìn)一步擴(kuò)展該功能以支持刪除員工的操作。
步驟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處理函數(shù)傳遞給EmployeeList組件,該組件將進(jìn)一步將其傳遞給它的子容器:
render() {return (<div><AddEmployee addEmployee={this.addEmployee}/><EmployeeList employees={this.state.employees} deleteEmployee={this.deleteEmployee}/></div>)}最終, ReactApp組件應(yīng)如下所示:
'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方法中的更改一起導(dǎo)入,以具有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組件以進(jìn)行渲染– DeleteEmployee組件通過(guò)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:在組件目錄內(nèi)創(chuàng)建delete-employee組件:
cd react-app/app/components/ touch delete-employee.jsx并復(fù)制以下內(nèi)容:
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)函數(shù)在Delete按鈕單擊時(shí)調(diào)用,這將進(jìn)一步使用props調(diào)用ReactApp中定義的deleteEmployee處理程序。
一切就緒后,目錄結(jié)構(gòu)應(yīng)如下所示:
現(xiàn)在,重新運(yùn)行該應(yīng)用程序并訪問(wèn)http:// localhost:8080 ,一旦您添加了幾名員工,它應(yīng)如下圖所示。
完整的源代碼托管在github上 。
翻譯自: https://www.javacodegeeks.com/2017/05/handling-events-react.html
react 事件處理
總結(jié)
以上是生活随笔為你收集整理的react 事件处理_在React中处理事件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 济南车备案要预约吗(济南车备案)
- 下一篇: java Linux安装(java li