//拆分组件结构,编写静态组件,编写动态组件,组件交互
//组件传值,子组件如何更改父组件的状态,在父组件重定义方法传递给子组件
class App extends React.Component{
constructor(props){
super(props)
this.state = {
todos:["吃饭","睡觉","打豆豆"]
}
this.Addtodo = this.Addtodo.bind(this)
}
//添加todo
Addtodo(todo){
const todos = this.state.todos
todos.unshift(todo)
this.setState({
todos
})
}
render(){
return (
<div>
<h1>Simple TODO List</h1>
<Add Addtodo={this.Addtodo} todos={this.state.todos}/>
<List todos={this.state.todos}/>
</div>
)
}
}
class Add extends React.Component{
constructor(props){
super(props)
this.HandleClick = this.HandleClick.bind(this)
}
HandleClick(){
//在父组件中添加数据
const todo = this.Todoinput.value.trim() //检验
if(!todo){
return
}
//调用父类的方法
this.props.Addtodo(todo);
//清空输入框
this.Todoinput.value = "";
}
render(){
return(
<div>
<input ref={input => this.Todoinput = input} type="text"/>
<button onClick={this.HandleClick}>Add #{this.props.todos.length+1}</button>
</div>
)
}
}
Add.propTypes = {
todos : PropTypes.array.isRequired,
Addtodo :PropTypes.func.isRequired
}
class List extends React.Component{
render(){
return (
<ul>
{this.props.todos.map((todo,index)=>{
return (<li key={index}>{todo}</li>)
})}
</ul>
)
}
}
//参数必须传递,并且是一个数组
List.propTypes = {
todos : PropTypes.array.isRequired
}
ReactDOM.render(<App/>,document.getElementById("example"))