在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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/350590.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ITK读图VTK显示

ITK 实现图像数据的读取&#xff0c;然后通过连接器把ITK读取的图像数据传输到VTK 然后进行显示。 #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageToVTKImageFilter.h" #include "itkJPEGImageIOFactory.h&qu…

python如何读二进制文件_python怎么读二进制文件

实际项目中经常遇到读取二进制问题&#xff0c;Python下读取二进制文件一般用Python的文件打开读写相关函数和struct. python学习网&#xff0c;大量的免费python视频教程&#xff0c;欢迎在线学习&#xff01; 1。获取文件名filename&#xff0c;可用对话框,也可以直接手写 2。…

第一阶段冲刺07

第一阶段冲刺07 昨天做了什么&#xff1a;学习了sqlite&#xff0c;但了解到开发非单机App&#xff0c;sqlite不适用于作为后台数据库。 今天准备做什么&#xff1a;学习http协议与Android通过服务器连接MySQL的知识。 遇到的困难&#xff1a;对于开发非单机版App的数据库的选择…

horizon client 无法识别域_「领域驱动设计DDD」事件风暴简介:实现域驱动设计的简便方法...

事件风暴是一种快速&#xff0c;轻量级且未得到充分认可的群体建模技术&#xff0c;它对于加速开发团队而言非常强大&#xff0c;有趣且有用。作为Alberto Brandolini的心血结晶&#xff0c;它是Gamestorming和领域驱动设计&#xff08;DDD&#xff09;原则的综合学习实践。该技…

第十篇 数据类型总结

第十篇 数据类型总结 ## 1 按可变类型or不可变类型 可变数据类型不可变数据类型列表数字字典字符串集合元组## 2 按有序or无序 有序无序字符串字典列表集合元组/数字不存在有序或无序一说## 3 按访问类型&#xff08;查&#xff09; 直接访问顺序访问&#xff08;序列类型&…

OpenCV cvtColor()函数

cv::cvtColor()用于将图像从一个颜色空间转换到另一个颜色空间的转换&#xff08;目前常见的颜色空间均支持&#xff09;&#xff0c;并且在转换的过程中能够保证数据的类型不变&#xff0c;即转换后的图像的数据类型和位深与源图像一致。 void cv::cvtColor(cv::InputArray s…

python读取csv某些行_【Python】Python 读取csv的某行或某列数据

站长用Python写了一个可以提取csv任一列的代码&#xff0c;欢迎使用。 Github链接 csv是Comma-Separated Values的缩写&#xff0c;是用文本文件形式储存的表格数据&#xff0c;比如如下的表格&#xff1a;就可以存储为csv文件&#xff0c;文件内容是&#xff1a; No.,Name,Ag…

logback slf4j_强制Tomcat通过SLF4J / Logback登录

logback slf4j因此&#xff0c;您将JAR可执行Web应用程序与Tomcat捆绑在一起 &#xff08;请务必先阅读其中一个&#xff09;。 但是&#xff0c;一开始就有这些烦人的Tomcat日志&#xff0c;它们独立于我们的应用程序日志且不可自定义&#xff1a; Nov 24, 2012 11:44:02 PM …

APP测试点总结

1 功能测试 根据产品需求文档编写测试用例  软件设计文档编写测试用例2 兼容性测试 适配性测试手机不同分辨率支持&#xff0c;客户端支持的分辨率等  手机不同版本的支持  手机不同厂家系统的支持  手机不同尺寸的支持安装&#xff0c;卸载测试生成的apk文件在真机上可…

threshold()

一、threshold()函数 1.1 threshold()函数各参数详解 double threshold(InputArray src,OutputArray dst,double thresh,double maxval,int type) 第一个参数&#xff0c;InputArray类型的src&#xff0c;输入数组&#xff0c;填单通道 , 8或32位浮点类型的Mat即可。 第…

如何提升python编程能力_Python编程小白如何提升自己的编程能力

1.不使用分号 使用分号在Python中是可选的&#xff0c;对比其他面向对象语言&#xff0c;你不需要在每一条语句后面使用分号。 这看起来很简单&#xff0c;似乎也节省不了多少时间;但一旦你的代码量扩展到数千号&#xff0c;这些分号就变得分心且没有必要键入。 2.找一个称手的…

javascript时间戳和日期字符串相互转换代码

一、日期字符串转时间戳 // 获取当前时间戳(以s为单位)// 第一种方式var timestamps new Date();timestamps timestamps / 1000;// 第二种方式var timestamp Date.parse(new Date());timestamp timestamp / 1000;// 第三种方式var date new Date("2014-07-10 10:21:1…

如何使用Spring设置安全的REST API

众所周知&#xff0c; Spring Boot是一个工具包&#xff0c;可以快速轻松地开发功能强大的Web服务。 它非常模块化&#xff0c;可以与其他框架和工具很好地配合使用。 在本教程中&#xff0c;我将向您展示通过使用Speedment作为ORM对现有SQL数据库设置RESTful API多么容易。 背…

OpenCV imread()函数

imread&#xff08;const string& filename, int flags1&#xff09; 例如&#xff1a; //读入图像单通道&#xff0c;即灰度图 ScrImage imread("C:\\Users\\Desktop\\opencv_1.jpg", 0);imread函数从文件中加载图像并返回该图像。如果该图像不能被读取&#x…

layui横向时间线_炒股一生只买一种股票:股价K线形成这样后,必然有一波拉升...

在上升趋势中做多; 在下跌趋势中做空; 在震荡区间顶部做空、底部做多。大趋势像是遛狗的主人&#xff0c;他走的比较慢&#xff1b;狗就像中短期的走势&#xff0c;活蹦乱跳&#xff0c;有时候跑过头&#xff0c;又会回来找主人一下&#xff0c;然后再去东闻闻、西嗅嗅。最后你…

最小二乘

1.最小二乘的背景 这种东东的来源&#xff0c;比较容易找到而且比较靠谱的途径自然是wiki百科了&#xff0c;以下部分的内容来自wiki百科&#xff1a; 1801年&#xff0c;意大利天文学家朱赛普皮亚齐发现了第一颗小行星谷神星。经过40天的跟踪观测后&#xff0c;由于谷神星运…

团队冲刺计划第八天

1、 所有工作的预期时间&#xff1a;96h 目前已经花的时间:78h 还剩余的时间:18h 2、任务看板 3、冲刺会议照片&#xff1a; 4、燃尽图&#xff1a; 转载于:https://www.cnblogs.com/532BEST/p/10871189.html

[Linux]Linux下经常会用到的简单实例(持续更新)

1、查找某些进程并结束他们&#xff1a; ps -elf | grep 进程关键字 | awk {print $4}| xargs kill -9 解析&#xff1a; ps -elf 的 -e 代表列出所有进程&#xff0c;-l 代表长格式&#xff0c;-f 代表完整的格式 grep的工作方式是这样的&#xff0c;它在一个或多个文件中搜索…

elupload获取文件名与路径_Uipath获取文件名,路径,扩展名等操作

Uipath获取文件名&#xff0c;路径&#xff0c;扩展名等操作东京IT青年前线​www.rpatokyo.com使用Assign Activity&#xff0c;声明一个字符串变量为str获取文件路径代码System.IO.Path.GetDirectoryName(“C:UsersAdministratorDesktop备课二回目css基础.pptx”)运行&#xf…