<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://unpkg.com/prop-types@15.6/prop-types.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
class App extends React.Component{
constructor(props){
super(props)
this.state = {
todos:['111','222','333']
}
this.addTodo = this.addTodo.bind(this)
}
// 01父组件定义函数
addTodo(todo){
const {todos}=this.state
todos.unshift(todo)
// // 更新
this.setState({todos})
}
render(){
return(
<div>
<h1>simple todolist</h1>
<Add count={this.state.todos.length} addTodo={this.addTodo}/>
<List todos={this.state.todos}/>
</div>
)
}
}
class Add extends React.Component{
constructor(props){
super(props)
this.add = this.add.bind(this)
}
add(){
// 1.读取输入的数据
const todo = this.todoinput.value.trim()
// 2.检查合法性
if(todo==''){
return
}
// 3.添加
this.props.addTodo(todo)
}
render(){
return(
<div>
<input type="text" ref={input=>this.todoinput = input}/>
<button onClick={this.add}>add #{this.props.count+1}</button>
</div>
)
}
}
Add.propTypes={
count:PropTypes.number.isRequired,
addTodo:PropTypes.func.isRequired
}
class List extends React.Component{
render(){
const {todos} = this.props
// console.log( this.props.todos)
return(
<ul>
{
todos.map((todo,index)=><li key={index}>{todo}</li>)
}
</ul>
)
}
}
List.propTypes={
todos:PropTypes.array.isRequired
}
ReactDOM.render(<App/>,document.getElementById('example'))
</script>
</body>
</html>
效果
Video_2020-10-11_121101.gif