前端之家收集整理的这篇文章主要介绍了
前端那些事之react篇--todomvc,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
react实现
目录结构
index.js
var React = require('react'),ReactDOM = require('react-dom'),App = require('./App/index.js'),Todo = require('./to-do/index');
require('./index.css');
ReactDOM.render(
<Todo />,document.getElementById('root')
);
todo文件下的index.js
import React from 'react'
import TodoList from './to-do-list'
function id() {
return Math.random().toString().replace(/\./,'')+'-'+Math.random().toString().replace(/\./,'')
}
var TodoMVC = React.createClass({
getInitialState:function () {
return {
items : [
{text:'aaa',id:id(),type:'active'},{text:'bbb',type:'no-active'},{text:'ccc',id:id()}
],value:'inp'
}
},render:function () {
return (
<div className="todo-mvc">
<h3>todos</h3>
<p>
<input value={this.state.value} onChange={this.handleChange}/>
<button onClick={this.handleAdd}>提交</button>
</p>
<TodoList
items={this.state.items}
onDelete={this.handleDelete}
onEdit={this.handleEdit}
/>
</div>
)
},handleEdit:function (obj) {
alert(obj.text)
var items = this.state.items;
items = items.map(function (o) {
console.log(obj.id,o.id)
if(o.id == obj.id){
o.text = obj.text
}
return o
})
console.log(items)
this.setState({items:items})
},handleDelete:function (obj) {
var items = this.state.items,json = []
for(var i=0;i<items.length;i++){
if(items[i].id != obj.id){
json.push(items[i])
}
}
this.setState({items:json})
},handleAdd:function () {
var items = this.state.items,text = this.state.value
items.push({
text:text,id:id()
})
this.setState({
items:items,value : ''
})
},handleChange:function (e) {
this.setState({
value:e.target.value
})
}
})
module.exports = TodoMVC
todo文件下的to-do-list文件里的index
import React from 'react'
var TodoItem = React.createClass({
getInitialState:function () {
return {
value : this.props.text
}
},render:function () {
return (
<li>
{this.props.text}<button onClick={(e)=>this.props.delete(this.props.o)}>删除</button><br/>
<input value={this.state.value} onChange={this.handleChange}/>
<button onClick={this.handleEdit}>确定</button>
<button onClick={this.handeCancel}>取消</button>
<br/><br/>
</li>
)
},handeCancel:function () {
this.setState({
value:this.props.text
})
},handleChange:function (e) {
this.setState({
value:e.target.value
})
},handleEdit:function () {
var obj = {
id:this.props.id,text:this.state.value
}
this.props.edit(obj)
}
})
var TodoList = React.createClass({
render:function () {
var that = this
var nodes = this.props.items.map(function (o) {
return (
<TodoItem id={o.id} edit={that.props.onEdit} o={o} key={o.id} text={o.text} delete={that.props.onDelete}/>
)
})
return (
<ul>{nodes}</ul>
)
}
})
module.exports = TodoList