需求
利用React实现一个简易的信息管理系统。
写的不太好,欢迎熟悉React的大神来找茬。真心感激!
分析
编写React就是不断构建组件的过程,首先要根据需求进行UI的划分:
-StudentBox -StudentList -Student -StudentForm
编码
服务端
没有用到服务器,采用了数据模拟的方式
var id = 41060122; //添加信息时自增长IDvar data = [ { id: 41060120, name: 'Mary', age: 20 }, { id: 41060121, name: 'Jacky', age: 18 }, { id: 41060122, name: 'Helen', age: 21 }];
页面
React
组件
StudentBox
var StudentBox = React.createClass({ getInitialState: function () { return {data: data}; }, //删除 handleDelete: function (index) { this.state.data.splice(index, 1); this.forceUpdate(); }, //更新 handleUpdate: function (student) { this.state.data.forEach(function (item) { if (item.id === student.id) { _.extend(item, student); } }); this.forceUpdate(); }, //新增 handleSave: function (student) { this.state.data.push(_.extend(student, {id: ++id})); this.forceUpdate(); }, render: function () { return () }});Student Messages
StudentList
var StudentList = React.createClass({ render: function () { var handleDelete = this.props.delete; var handleUpdate = this.props.update; return (})}
index | number | name | age | operation |
---|
Student
var Student = React.createClass({ getInitialState: function () { return {isEdit: false}; }, handleEdit: function () { this.setState({isEdit: !this.state.isEdit}); }, handleDelete: function (index) { this.props.delete(index); }, handleUpdate: function (id) { var name = React.findDOMNode(this.refs.name).value.trim(); var age = React.findDOMNode(this.refs.age).value.trim(); if (!name || !age) { return; } this.props.update({ id: id, name: name, age: age }); this.handleEdit(); }, render: function () { var index = this.props.index; var student = this.props.data; var operations = this.state.isEdit ?:; var name = this.state.isEdit ? : student.name; var age = this.state.isEdit ? : student.age; return ( {index} {student.id} {name} {age} {operations} ) }});
StudentForm
var StudentForm = React.createClass({ handleSubmit: function (e) { e.preventDefault(); var name = React.findDOMNode(this.refs.name).value.trim(); var age = React.findDOMNode(this.refs.age).value.trim(); if (!name || !age) { return; } this.props.save({ name: name, age: age }); }, render: function () { return () }});
渲染
React.render(, document.body);