react 父子组件通信(第二篇)
# react 父子组件通信(第二篇)

# 计数器 子
// 计数器 子
function ChildCount({ value, onClick }) {
const handleChildChange = e => {
onClick(e)
}
return (
<>
<Input
placeholder='子传父'
onChange={e => handleChildChange(e.target.value)}
allowClear
/>
<div>父组件传的数据👉:{value}</div>
</>
)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 视频播放组件 子
// 视频播放组件 子
function ChildPlay({ onRef, onClick }) {
// 暴露出去
useImperativeHandle(onRef, () => {
return {
openPlay,
}
})
const ref = useRef(null)
const [isPlaying, setPlaying] = useState(false)
const openPlay = () => {
const nextIsPlaying = !isPlaying
setPlaying(nextIsPlaying)
onClick(nextIsPlaying)
if (nextIsPlaying) {
ref.current.play()
} else {
ref.current.pause()
}
}
return (
<>
<video
width='250'
ref={ref}
onPlay={() => setPlaying(true)}
onPause={() => setPlaying(false)}
>
<source
src='https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4'
type='video/mp4'
/>
</video>
</>
)
}
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
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
# 父子通信组件
// 父子通信组件
const FatherForm = () => {
const modalFormRef = React.createRef()
const handleClick = () => {
modalFormRef.current.open()
}
const inputRef = useRef(undefined)
const [count, setCount] = useState(0)
const handleCount = () => {
if (!inputRef.current) {
inputRef.current = 0
}
inputRef.current++
setCount(inputRef.current)
}
const [childValue, setChildValue] = useState('')
const childPlayOnRef = React.createRef()
const [isPlaying, setPlaying] = useState(false)
return (
<>
<Button onClick={handleClick}>父子通信</Button>
<ModalFormFK onRef={modalFormRef} title='测试表单'>
<Row gutter={20}>
<Col span={12}>
<Alert message='父组件' type='info' showIcon />
<Input
placeholder='父传子'
onChange={e => setCount(e.target.value)}
allowClear
/>
子组件传的数据👉{childValue}
</Col>
<Col span={12}>
<Alert message='子组件' type='error' showIcon />
<ChildCount
value={count}
onClick={e => {
setChildValue(e)
}}
/>
</Col>
</Row>
<Row>
<Col span={24}>
<Button
type='primary'
onClick={() => {
childPlayOnRef.current.openPlay()
message.success('父调用子的方法')
}}
>
{isPlaying ? '暂停' : '播放'}
</Button>
<Button onClick={handleCount}>计数传子</Button>
</Col>
<Col span={24}>
<ChildPlay onRef={childPlayOnRef} onClick={e => setPlaying(e)} />
</Col>
</Row>
</ModalFormFK>
</>
)
}
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
编辑 (opens new window)
上次更新: 2023/12/15, 15:07:46