我有一个按钮网格,其中包含我希望能够选择的选项。首先,所有值都设置为false。但是有一个问题,每次我第一次按一个按钮,它的值仍然是false,第二次是false (这没问题),第三次是按钮现在设置为true。我希望能够在第一次按下按钮时将值设置为true。
const {
// This value is 'false' at first
isArtAndCulture
} = stateController;
const [isAaC, setIsArtAndCulture] = useState(false);
...
<Block style={{ flex: 0.85, marginRight: 5 }}>
<TouchableOpacity
style={{
height: 44,
borderRadius: 5,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: isAaC ? theme.colors.EventSection : theme.colors.Grey
}}
onPress={() => {
setIsArtAndCulture(!isAaC);
// Supposedly the value must be 'true' now, but when I print the 'isArtAndCulture' value,
// it stays 'false' until the third button press.
saveInState({ isArtAndCulture: isAaC });
console.log(isArtAndCulture);
}}
>
<Text
profile
text="Arte y Cultura"
style={{
fontFamily: theme.fonts.Bold,
color: isAaC ? theme.colors.White : theme.colors.Black
}}
/>
</TouchableOpacity>
</Block>
saveInState = state => {
this.setState(state);
}发布于 2020-05-12 12:00:15
因为您正在使用
const [isAaC, setIsArtAndCulture] = useState(false);您可以通过setIsArtAndCulture更改isAaC的状态。
如果您使用的是useState,这意味着您使用的是functional component,因此不能使用this.,只能在class component中使用this.setState
更改此设置:
saveInState = state => {
this.setState(state);
}至:
saveInState = (val) => {
setIsArtAndCulture(val)
}一定要运行代码片段,希望能消除你的疑虑:
const { useState } = React;
const App = () => {
const [isAaC, setIsArtAndCulture] = useState(false);
const saveInState = (val) => {
setIsArtAndCulture(val);
}
return (
<div>
Current Val : {isAaC ? "True" : "False"}
<br/>
<button onClick={() => saveInState(true)}>Make True</button>
<button onClick={() => saveInState(false)}>Make False</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('react-root'));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>
发布于 2020-05-12 12:13:01
使用以前的状态,而不是直接反转变量isAaC,如下所示:
setIsArtAndCulture((prevState) => !prevState);https://stackoverflow.com/questions/61743546
复制相似问题