赞
踩
App组件
//App组件 class App extends React.Component{ constructor(props) { super(props); this.state={ todos:['吃饭','睡觉','敲代码'] } this.addTodo = this.addTodo.bind(this) } addTodo(todo){ //this.state.todos.unshift(todo) //不能这么写,需要setState才能更新state的内容 const {todos} = this.state todos.unshift(todo) this.setState({todos}) } render(){ return( <div> <h1>Simple TODO List</h1> <Add count={this.state.todos.length} addTodo={this.addTodo}/> <List todos = {this.state.todos}/> </div> ) } }
Add组件
//Add组件 class Add extends React.Component{ constructor(props) { super(props); this.handlerAdd = this.handlerAdd.bind(this) } render(){ return( <div> <input type="text" ref={input => this.todoInput = input}/> <button onClick={this.handlerAdd}>add #{this.props.count+1}</button> </div> ) } handlerAdd() { //1.读取输入的数据 const todo = this.todoInput.value.trim() //2.检查合法性 if (! todo) return //3.添加 this.props.addTodo(todo) //4.清除输入 this.todoInput.value = "" } } Add.PropTypes={ count: PropTypes.number.isRequired, addTodo:PropTypes.func.isRequired }
List组件
//List组件
class List extends React.Component{
render(){
return(
<ul>
{
this.props.todos.map((todo,index) => <li key={index}>{todo}</li>)
}
</ul>
)
}
}
List.PropTypes={
todos:PropTypes.array.isRequired
}
ReactDOM.render(<App/>,document.getElementById('example'))
constructor(props) {
super(props);
this.state={
todos:['吃饭','睡觉','敲代码']
}
this.addTodo = this.addTodo.bind(this)
}
addTodo(todo){
//this.state.todos.unshift(todo) //不能这么写,需要setState才能更新state的内容
const {todos} = this.state
todos.unshift(todo)
this.setState({todos})
}
this.setState({todos})
render(){
return(
<div>
<h1>Simple TODO List</h1>
<Add count={this.state.todos.length} addTodo={this.addTodo}/>
<List todos = {this.state.todos}/>
</div>
)
}
const todo = this.todoInput.value.trim()
his.props.addTodo(todo)
handlerAdd() {
//1.读取输入的数据
const todo = this.todoInput.value.trim()
//2.检查合法性
if (! todo)
return
//3.添加
this.props.addTodo(todo)
//4.清除输入
this.todoInput.value = ""
}
Add.PropTypes={
count: PropTypes.number.isRequired,
addTodo:PropTypes.func.isRequired
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。