我有一个简单的页面,有两部分:一个标签,显示50%的时间后,页面加载,和一个'滚动'按钮,模拟滚动一个六面骰子的结果. 这两个部分都使用一个使用Math.Random的d6
函数.
这些应该是独立的部分.按下Roll按钮不应该影响是否显示"hello",但这就是发生的事情. 按下Roll按钮通常会使"Hello"出现和消失. 为什么会发生这种情况,我该如何阻止它?
代码Sandbox 这里:https://codesandbox.io/p/sandbox/summer-monad-457k9j?file=%2Fsrc%2FApp.tsx%3A5%2C1-35%2C2
export default function App() {
const [dieRollResult, setDieRollResult] = useState<number>(0);
const die = (size: number): number => {
return Math.floor(Math.random() * size) + 1;
};
const d6 = () => die(6);
const shouldLabelBeVisible = () => (d6() <= 3 ? "visible" : "hidden");
return (
<Stack>
<Typography visibility={shouldLabelBeVisible}>hello</Typography>
<Typography>{dieRollResult}</Typography>
<Button
onClick={() => {
setDieRollResult(d6());
}}
>
Roll
</Button>
</Stack>
);
}