复合组件通讯
组件之间如何通讯?
全局状态管理
父子组件,兄弟组件通讯
第一次处理子组件的事件,居然是这么写的?
jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function VoteV1({slots}){const [yesVotes,setYesVotes] = useState(0);const [noVotes,setNoVotes] = useState(0);return (<div><div className='row'>totle:{yesVotes+noVotes}</div><div className='flex'><VoteButton text='支持' votes={yesVotes} onClick={(yesVotes)=>setYesVotes(yesVotes+1)} /><div className="ds05"></div><VoteButton text='反对' votes={noVotes} onClick={(noVotes)=>setNoVotes(noVotes+1)} /></div></div>);}
修正后的代码如下:
jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function VoteV1({slots}){const [yesVotes,setYesVotes] = useState(0);const [noVotes,setNoVotes] = useState(0);return (<div><div className='row'>totle:{yesVotes+noVotes}</div><div className='flex'><VoteButton text='支持' votes={yesVotes} onClick={()=>setYesVotes(yesVotes+1)} /><div className="ds05"></div><VoteButton text='反对' votes={noVotes} onClick={()=>setNoVotes(noVotes+1)} /></div></div>);}
再次优化,使用函数式更新,避免闭包问题:
jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function VoteV1({slots}){const [yesVotes,setYesVotes] = useState(0);const [noVotes,setNoVotes] = useState(0);const handleYesClick = ()=>{setYesVotes(prev=>prev+1)}const handleNoClick = ()=>{setNoVotes(prev=>prev+1)}return (<div><div className='row'>totle:{yesVotes+noVotes}</div><div className='flex'><VoteButton text='支持' votes={yesVotes} onClick={handleYesClick} /><div className="ds05"></div><VoteButton text='反对' votes={noVotes} onClick={handleNoClick} /></div></div>);}
如果组件频繁更新,可能会使用上一个状态值,所以使用函数式更新更加安全.
注意事项:
是的!当只有一个参数时,它自动就是事件对象(event):