React实现todolist的方法

todoList.html: <!DOCTYPE html><html><head><link rel="stylesheet" href="todoList.css"><script src="build/react.js"></script><script src="bui...

todoList.html:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="todoList.css">
<script src="build/react.js"></script>
<script src="build/react-dom.js"></script>
<script src="build/browser.min.js"></script>
</head>
<body>
<div id="todoList"></div>
<script type="text/babel" src="todoList.jsx"></script>
</body>
</html>



todoList.jsx:

var TodoList = React.createClass({
getInitialState: function() {
return {lists: []}
},
addList: function(list) {
if (this.state.lists.indexOf(list) == -1) {
this.state.lists.push(list);
this.setState({lists: this.state.lists});
}
},
deleteList: function(index) {
this.state.lists.splice(index, 1);
this.setState({lists: this.state.lists});
},
render: function() {
return (
<div>
<AddList addList={this.addList} />
<DeleteList deleteList={this.deleteList} lists={this.state.lists} />
</div>
);
}
});
var AddList = React.createClass({
addList: function(e) {
e.preventDefault();
this.props.addList(this.refs.textInput.value);
this.refs.textInput.value = "";
},
render: function() {
return (
<form onSubmit={this.addList}>
<input type="text" placeholder="Please enter your name!" ref="textInput" autoComplete="off"/>
</form>
);
}
});
var DeleteList = React.createClass({
deleteList: function(e) {
var index = e.target.getAttribute('id');
this.props.deleteList(index);
},
render: function() {
return (
<ul>
{
this.props.lists.map(function(list, index) {
return (
<li key={index}> 
{list}
<button id={index} onClick={this.deleteList}>x</button>
</li>
);
}.bind(this))
}
</ul>
);
}
});
ReactDOM.render(
<TodoList />,
document.getElementById("todoList")
);

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
廖雪
廖雪

78 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. bngvkjlajj 0 文章