1. 程式人生 > >spring-boot react一步一步實現增刪改查 元件化

spring-boot react一步一步實現增刪改查 元件化

spring-boot react一步一步實現增刪改查 中,用一個元件實現了表格和表單功能,所以現在需要將其拆分成元件獨立出來

拆分表格

  1. 建立Table.js
import React, {Component} from 'react'

class Table extends Component {
    render() {
        return (
            <table className="table table-bordered">
                <thead>
                <
tr> <th>ID</th> <th>使用者名稱</th> <th>操作</th> </tr> </thead> <tbody> { this.props.list.map(item => { return
( <tr key={item.id}> <td>{item.id}</td> <td>{item.name}</td> <td> <button className="btn btn-primary" onClick=
{() => { this.props.edit(item); }}>修改 </button> <button className="btn btn-danger" style={{marginLeft: '5px'}} onClick={() => { this.props.deleteItem(item) }}>刪除 </button> </td> </tr> ) }) } </tbody> </table> ) } } export default Table
  1. 替換App.js中的表格
 <div className="col-xs-4 col-xs-offset-1">
    <Table list={this.state.list} edit={this.edit} deleteItem={this.deleteItem}></Table>
 </div>
  1. App.js中處理表格中的修改按鈕點選事件
edit = (item) => {
    this.setState({
        id:item.id,
        name:item.name
    })
}

拆分表單元件

  1. 新增Form.js
import React,{ Component } from 'react'

class From extends Component{
    render(){
        return (
            <form className="form-horizontal">
                <div className="form-group">
                    <label htmlFor="name" className="col-xs-3">使用者名稱</label>
                    <div className="col-xs-8">
                        <input type="text" id="name" className="form-control" value={this.props.name} onChange={(e)=>{this.props.handleChange(e.target.value)}}/>
                    </div>

                </div>
                <div className="form-group">
                    <div className="col-sm-offset-2 col-sm-10">
                        <button className="btn btn-default" onClick={this.props.submit}>提交</button>
                    </div>
                </div>
            </form>
        )
    }
}

export  default From

2.App.js中修改相應的處理邏輯

  • 文字框中的change事件處理
handleChange = (name) =>{
    this.setState({
        name
    });
}

原始碼 https://gitee.com/qinaichen/react-crud.git 中的gis分支