【问题标题】:How to select a button in React Native, without selecting others?如何在 React Native 中选择一个按钮,而不选择其他按钮?
【发布时间】:2021-05-31 02:07:18
【问题描述】:

我有一个简单的测验应用程序,它总是有相同的答案,每个答案都有不同的分数。

当 USER 按下时,我希望选择按钮,更改颜色,将 id 传递给状态。 当 USER 按下另一个按钮时,我想取消选择第一个按钮并选择它。

使用 React 函数式组件、ReactHooks、样式化组件和 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;
;

【问题讨论】:

    标签: typescript react-native styled-components react-functional-component


    【解决方案1】:

    您可以通过添加包含所选按钮 id 的状态来实现此目的

    const [selectedButton, setSelectedButton] = useState(0)
    
    const handleAnswer = (id) => {
       setSelectedButton(id)
    }
    
    return (
        <AnswerButton
           id="1"
           isSelected={selectedButton === "1"}
           style={shadow}
           onPress={() => handleAnswer("1")}
        />
    )
    

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 2021-09-01
      • 2021-09-30
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多