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分支

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章