日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

在React中处理事件

發布時間:2023/12/3 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在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中处理事件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。