javascript - 如何确保 React 钩子中的状态不会过时
问题描述
我在下面创建的按钮似乎落后于selectedButtonIdx
价值。
被称为toggleSelected
不完整的时间getClass
?
function ButtonGroup(props) {
const [selectedButtonIdx,setIdx]=useState(props.loadCurrentAsIndex);
const toggleSelected = (e) => {
setIdx(parseInt(e.target.dataset.index));
props.onclick(e);
};
const getClass = (index) => {
return (selectedButtonIdx === index) ? classnames('current', props.btnClass)
: classnames(props.btnClass)
};
let buttons = props.buttons.map((b, idx) => <Button key={idx} value={b.value} index={idx} text={b.text}
onclick={e => toggleSelected(e)}
btnClass={getClass(idx)}/>);
return (
<div>
{buttons}
</div>
);
}
每个 onclick 都希望通过更改其类向用户显示组中的哪个按钮被单击。
解决方案
看着这个,
<Button
key={idx}
value={b.value}
index={idx}
text={b.text}
onclick={e => toggleSelected(e)}
btnClass={getClass(idx)}
/>
Button
是您的自定义组件,
这里需要注意两点,
- 您提供了
onclick
(c
很小的)道具,在您的实际组件中应该是onClick={props.onclick}
- 您已经使用
e.target.dataset.index
, 来处理dataset
我们应该有带data-
前缀的属性。所以你index
应该data-index
在你的实际组件中。
所以最后你的Button
组件应该是,
const Button = (props) => {
return <button text={props.text} data-index={props.index} onClick={props.onclick} className={props.btnClass}>{props.value}</button>
}
推荐阅读
- node.js - 当都安装在 kubernetes 中时,如何在节点 js 中使用用户 jaeger?
- php - 无法通过 ssl 将 Laravel 应用程序连接到托管在 Azzure 上的数据库
- mysql - 十月CMS | 在 Models/Model_Name/fields.yaml 中,当我选择的列为空时,如何使用 select: 连接但删除字符
- android - 为什么小米红米 Note 6 Pro 不支持 ARCore?
- java - 我如何按顺序简化方向数组 {"south", "east"} 等?
- sql - 如何对多行的列值求和?
- asp.net-mvc - AspNet 在请求查询时按用户名对消息进行分类
- database - 如何管理微服务上的多个数据库?
- css - 使用 CSS 使标题变粘并滚动正文
- gnuplot - 如何将gnuplot公式放入变量中