试图解决这个问题,但没有任何效果。尝试在 useState 上执行 onClick 和切换类,但是当我执行此操作时会触发任何内容。谁能解释一下为什么它不起作用。React 似乎没有改变状态,我也看不到应该出现在按钮中的 x,这是应该将 useState 设置为 false 的那个。提前致谢。
import React, { useState } from 'react';
import Button from '@material-ui/core/Button';
import FilterMenu from "./selectButton";
import FetchRandomBet from "./fetchRandomBets";
function Betslip() {
const data = [
{
value: 0,
label: "No Filter"
},
{
value: 1,
label: "Less than two"
},
{
value: 2,
label: "More than two"
},
]
const [selectedValue, setSelectedValue] = useState(0);
const [allStakes, setAllStakes] = useState(null);
const [isActive, setActive] = useState(false);
const handleChange = obj => {
setSelectedValue(obj.value);
}
const betNow = () => {
if (!allStakes) {
const stakes = localStorage.getItem("stakes");
const jsnStake = JSON.parse(stakes) || [];
setAllStakes([jsnStake]);
setActive(isActive);
console.log('yes')
} else if (allStakes) {
localStorage.setItem("stakes", null);
setAllStakes([])
console.log('no')
}
}
const closeBet = () => {
setActive(false);
}
console.log(allStakes)
return (
<div className="betslip">
<div className="betslip-top">
<h1 className="text">BETSLIP</h1>
<p className="text-two">BET WITH US!</p>
<div>
<FilterMenu
optionsProp={data}
valueProp={selectedValue}
onChangeProp={handleChange}
/>
</div>
</div>
<div>
<FetchRandomBet
valueProp={selectedValue}
/>
</div>
<Button
onClick={betNow}
className="betnow"
variant="contained"
>
Bet Now!
</Button>
<div className={isActive ? "bet-show" : "bet-noshow"}>
<button
onClick={closeBet}
>
x
</button>
<h1>
{allStakes}
</h1>
</div>
</div >
);
}
export default Betslip;
答案 0 :(得分:1)
默认情况下,您的活动设置为 false 并且您有 css 类显示活动是否为 true 我认为
所以在你的 betNow() 中:
const betNow = () => {
if (!allStakes) {
const stakes = localStorage.getItem("stakes");
const jsnStake = JSON.parse(stakes) || [];
setAllStakes([jsnStake]);
// change to true
setActive(true);
console.log('yes');
} else if (allStakes) {
localStorage.setItem("stakes", null);
setAllStakes([]);
console.log('no');
}
}