react学习笔记–组合组件使用__交互
这个和官网上的效果差不多,内有详细批注。
这个是效果图,点击add把文本框的内容添加到下面的list中
<!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>
</head>
<body>
<div id="example"></div>
<script src="../js/react.development.js"></script>
<script src="../js/react-dom.development.js"></script>
<script src="../js/prop-types.js"></script>
<script src="../js/babel.min.js"></script>
<script type="text/babel">
/*
组件化编写功能的流程
1.拆分组件
2.实现静态组件(只有静态界面,没有动态数据和交互)
3.实现动态组件
(1)实现初始话数据
(2)实现交互功能
*/
class App extends React.Component{
constructor(props){
super(props)
//赋初值
this.state = {
todos: ['吃饭','睡觉','打代码']
}
//绑定addTodo的this
this.addTodo = this.addTodo.bind(this)
}
//需要在父组件中写一个addTodo改变todos的状态
addTodo(todo){
const {todos} =this.state
//添加
todos.unshift(todo)
//改变状态
this.setState({todos})
}
render()
{
//Add中添加两个属性 一个count 一个addTodo 到 props中
const {todos} = this.state
return (
<div>
<h1>Simple TODO LIST</h1>
<Add count = {todos.length} addTodo ={this.addTodo}/>
<List todos = {todos}/>
</div>
)
}
}
//在子组件中改变父组件的状态,不能直接改,
//
class Add extends React.Component{
constructor(props){
super(props)
this.add = this.add.bind(this)
}
add(){
const todo = this.todoInput.value.trim()
//内容为空直接返回
if(!todo){
return
}
this.props.addTodo(todo)
//清空文本框中的内容
this.todoInput.value = ""
}
render()
{
// count = todos.length
// count 是从上面的父组件传过来的
//ref 获取标签
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()
{
// map添加li ,key 是 下标
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'))
</script>
</body>
</html>