React:onClick中同时执行Prop函数与状态更新的语法问题
React按钮onClick同时执行Prop函数与状态更新的问题解决
你遇到的核心问题是没有真正调用传入的Prop函数——你只是写了函数名(比如showAll),这只是引用函数本身,不会触发执行,必须加上括号()才会调用函数。
修正内联onClick写法
把每个按钮的onClick里的Prop函数加上括号调用:
const TaskFilter = ({ showActive, showAll, showCompleted }) => { const [activeBtn, setActiveBtn] = useState('All') return ( <div className="task-filter"> <Button text='All' onClick={() => { showAll(); setActiveBtn('All') }} activeBtn={activeBtn} /> <Button text='Active' onClick={() => { showActive(); setActiveBtn('Active') }} activeBtn={activeBtn}/> <Button text='Completed' onClick={() => { showCompleted(); setActiveBtn('Completed') }} activeBtn={activeBtn} /> </div> ) }
修正封装的handleClick函数
如果想用封装的函数,同样要在函数里调用传入的action:
const TaskFilter = ({ showActive, showAll, showCompleted }) => { const [activeBtn, setActiveBtn] = useState('All') const handleClick = (action, id) => { action(); // 这里要加括号执行函数 setActiveBtn(id); } return ( <div className="task-filter"> <Button text='All' onClick={() => handleClick(showAll, 'All')} activeBtn={activeBtn} /> <Button text='Active' onClick={() => handleClick(showActive, 'Active')} activeBtn={activeBtn}/> <Button text='Completed' onClick={() => handleClick(showCompleted, 'Completed')} activeBtn={activeBtn} /> </div> ) }
这样点击按钮时,既会执行传入的排序函数(更新列表),也会更新本地的激活按钮状态。
内容的提问来源于stack exchange,提问作者Tyubit
相关产品推荐
相关产品推荐

