index.js 外部老生畅谈 主要是循环用到了array.map
组件需要一层层传递 如果需要透传可以使用{...todo}
TodoItemList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import React, { Component } from 'react' import TodoItem from "./TodoItem";
export default class TodoList extends Component { render() { console.log(this.props) return ( <ul> { this.props.todos.map(todo => { return ( <TodoItem key={todo.id} {...todo} /> // <TodoItem // key={todo.id} // id={todo.id} // title={todo.title} // isCompleted={todo.isCompleted} // /> ) }) } </ul> ) } }
|
TodoItem
1 2 3 4 5 6 7 8 9 10 11 12
| import React, { Component } from 'react'
export default class TodoItem extends Component { render() { return ( <li> {this.props.title}{this.props.isCompleted ? '已完成' : '未完成'} </li> ) } }
|
数据改变
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import React, { Component } from 'react'
export default class Like extends Component { constructor() { super() this.state = { isLiked: false } }
handleLikedClick = () => {
console.log('setstate外部先驱的this.state.isLiked:', this.state.isLiked) this.setState((prevState) => { console.log(prevState) console.log('setstate内部的this.state.isLiked:', this.state.isLiked) return { isLiked: !prevState.isLiked } }, () => { console.log(this.state) }) console.log('setstate外部后续的this.state.isLiked:', this.state.isLiked)
}
render() { return ( <div> <span onClick={this.handleLikedClick}> {this.state.isLiked.toString()}: {this.state.isLiked ? '取消❤️' : '喜欢'} </span> </div> ) } }
|