1,父子组件
1 | //子组件 Child |
1 | //父组件 Parent |
2,父子组件组合方式
1.
1
2
3
4
5
6
7
8
9import React from 'react'
import Parent from './Parent'
import Child from './Child'
export default function () {
return <Parent>
<Child></Child>
</Parent>
}
这种情况,当点击```Parent``` 组件的按 钮+1的时候,子组件```Child```不会刷新
2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import React, { useState } from 'react'
export default function Parent() {
const [count, setCount] = useState(0)
console.log("parent", count)
return <div>
<div>Parent {count}</div>
<button onClick={() => setCount(count + 1)}>Click +1</button>
<Child />
</div>
}
export function Child() {
console.log("child")
return <div>Child</div>
}
这种情况,当点击Parent
组件的按 钮+1的时候,子组件Child
会刷新
3.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import React, { useState, memo } from 'react'
export default function Parent() {
const [count, setCount] = useState(0)
console.log("parent", count)
return <div>
<div>Parent {count}</div>
<button onClick={() => setCount(count + 1)}>Click +1</button>
<Child />
</div>
}
const Child = memo(() => {
console.log("child")
return <div>Child</div>
})
这种情况,当点击Parent
组件的按 钮+1的时候,子组件Child
不会刷新 ,只有memo的依赖变化才会刷新,当然内部逻辑也可以触发自己刷新,这里不探讨。