In this section, we want to click the check box to modify the real-time status of the task item, but the Item
component and the App
component have an ancestor-grandson relationship. If it is not a parent-child relationship, can we still communicate usingprops
? The answer is yes.
Define an update function in the App component and pass it to the Item component
- 1. Define a function that updates status data
// 更新状态数据
updateTodo = () => {
const {
todos } = this.state
console.log(todos)
}
- 2. First pass it to the List component
render() {
const {
todos,updateTodo} = this.props
return (
<ul className="todo-main">
{
todos.map(todo=>{
return <Item key={
todo.id} {
...todo} updateTodo={
updateTodo}/>
})
}
</ul>
)
}
- 3. Define a callback for the onChange event in the Item component.
import React, {
Component } from 'react'
import "./index.css"
export default class Item extends Component {
// 初始化状态数据
state = {
mouseIn:false}
// 鼠标移入移出回调函数
mouseHandle = (flag) => {
this.setState({
mouseIn:flag})
}
// 更新任务项状态
checkHandle = (id,event) => {
this.props.updateTodo(id,event.target.checked)
}
render() {
const {
id,name,done} = this.props
const {
mouseIn} = this.state
return (
<li onMouseEnter={
()=>this.mouseHandle(true)} onMouseLeave={
()=>this.mouseHandle(false)} style={
{
backgroundColor: mouseIn?'gainsboro':''}}>
<label>
<input type="checkbox" defaultChecked={
done} onChange={
event=>this.checkHandle(id,event)}/>
<span>{
name}</span>
</label>
<button className="btn btn-danger" style={
{
display:mouseIn?"block":"none"}}>删除</button>
</li>
)
}
}
We bound an onChange callback function to the check boxcheckHandle(id,event)
and passed id
and event
as parameters . When we click the checkbox, we pass the parameters to the updateTodo
function and let it modify the App
component's state data.
- 4. Transform the updateTodo function
// 更新状态数据
updateTodo = (id,done) => {
const {
todos } = this.state
const newTodos = todos.map(todoObj=>{
if (id === todoObj.id) return {
...todoObj,done}
return todoObj
})
this.setState({
todos:newTodos})
}
Here we determine that if the id
value matches the id
value in the list, we will update the status of the done
value , otherwise no changes are made and returned as is.
- 5. Specific effects
We can see from the picture that when we click the check box in the list and modify the status of the task item,react
in the developer toolsstate
The value will also change in real time. At this point, it means that we have completed the real-time update of the data.
Summary
- To get the status value of a checkbox use:
event.target.checked
- Communication between ancestor and grandchild components can also be passed using props.