如何在 React Native 中 select 一个按钮,而不 select 其他按钮?
How to select a button in React Native, without selecting others?
我有一个简单的测验应用程序,它总是有相同的答案,每个答案都有不同的分数。
当 USER 按下时,我希望按钮被 selected,改变颜色,将 id 传递给状态。
当用户按下另一个按钮时,我想取消 select 第一个按钮并 select 这个按钮。
使用 React 功能组件、ReactHooks、styled-components 和 TypeScript。
按钮:
<AnswerButton
id="1"
isSelected={isSelected}
style={shadow}
onPress={handleAnswer}
>
<AnswerText>Muito Correto</AnswerText>
</AnswerButton>
<AnswerButton
id="2"
style={shadow}
isSelected={isSelected}
onPress={handleAnswer}
>
<AnswerText>Moderadamente Correto</AnswerText>
</AnswerButton>
样式组件:
export const AnswerButton = styled.TouchableOpacity<AnswerProps>
background: ${darken(0.05, #EEEDED)};
border-radius: 35px;
padding: 15px;
margin-bottom: 25px;
border: 2px solid #64007b;
${props =>
props.isSelected &&
css
border-color: #c53030;
background-color: #fff8f7;
border-width: 2px;
}
;
export const AnswerText = styled.Text
color: #64007b;
font-family: 'RobotoSlab-Medium';
font-size: 18px;
line-height: 30px;
text-align: center;
;
您可以通过添加包含所选按钮 ID 的状态来实现此目的
const [selectedButton, setSelectedButton] = useState(0)
const handleAnswer = (id) => {
setSelectedButton(id)
}
return (
<AnswerButton
id="1"
isSelected={selectedButton === "1"}
style={shadow}
onPress={() => handleAnswer("1")}
/>
)
我有一个简单的测验应用程序,它总是有相同的答案,每个答案都有不同的分数。
当 USER 按下时,我希望按钮被 selected,改变颜色,将 id 传递给状态。 当用户按下另一个按钮时,我想取消 select 第一个按钮并 select 这个按钮。
使用 React 功能组件、ReactHooks、styled-components 和 TypeScript。
按钮:
<AnswerButton
id="1"
isSelected={isSelected}
style={shadow}
onPress={handleAnswer}
>
<AnswerText>Muito Correto</AnswerText>
</AnswerButton>
<AnswerButton
id="2"
style={shadow}
isSelected={isSelected}
onPress={handleAnswer}
>
<AnswerText>Moderadamente Correto</AnswerText>
</AnswerButton>
样式组件:
export const AnswerButton = styled.TouchableOpacity<AnswerProps>
background: ${darken(0.05, #EEEDED)};
border-radius: 35px;
padding: 15px;
margin-bottom: 25px;
border: 2px solid #64007b;
${props =>
props.isSelected &&
css
border-color: #c53030;
background-color: #fff8f7;
border-width: 2px;
}
;
export const AnswerText = styled.Text
color: #64007b;
font-family: 'RobotoSlab-Medium';
font-size: 18px;
line-height: 30px;
text-align: center;
;
您可以通过添加包含所选按钮 ID 的状态来实现此目的
const [selectedButton, setSelectedButton] = useState(0)
const handleAnswer = (id) => {
setSelectedButton(id)
}
return (
<AnswerButton
id="1"
isSelected={selectedButton === "1"}
style={shadow}
onPress={() => handleAnswer("1")}
/>
)