【问题标题】:Selecting button in React Native ButtonGroup在 React Native ButtonGroup 中选择按钮
【发布时间】:2021-09-30 10:21:07
【问题描述】:

我有一个小问题。我正在使用以前使用两个选项的 ButtonGroup,但现在我提供了 4 个选项。

它在屏幕上正确呈现,但我只能选择前两个选项。如何在选择之间跳转,以便选择不同的按钮。

欢迎任何帮助!

      <ButtonGroup
        selectedIndex={this.state.test === "First" ? 0 : 1}
        buttons={["First", "Second", "Third", "Fourth"]}
        containerStyle={{ height: 50 }}
        selectedButtonStyle={{ backgroundColor: "red" }}
        selectedTextStyle={{ color: "white" }}
        textStyle={{ fontSize: 18, fontWeight: '600' }}
        onPress={(selectedIndex) => 
          this.setState({
          test: buttons[selectedIndex]
        })}
      />

【问题讨论】:

    标签: typescript react-native buttongroup


    【解决方案1】:

    Index 可以保持在状态,然后可以分配给 onPress 中的 selectedIndex,它应该适用于不同按钮的选择

      this.state = {
       test: "First",
       btnIndex: 0
      }
    
      <ButtonGroup
        selectedIndex={this.state.btnIndex}
        buttons={["First", "Second", "Third", "Fourth"]}
        containerStyle={{ height: 50 }}
        selectedButtonStyle={{ backgroundColor: "red" }}
        selectedTextStyle={{ color: "white" }}
        textStyle={{ fontSize: 18, fontWeight: '600' }}
        onPress={(selectedIndex) => {
        this.setState({ 
        test: buttons[selectedIndex], 
        btnIndex: selectedIndex 
      });
        }}
      />
    

    【讨论】:

    • 您好,感谢您的回答,但用类似的答案解决了
    【解决方案2】:

    发生这种情况是因为您设置了 selectedIndex={this.state.test === "First" ? 0 : 1},因此您只有 2 个索引(和 4 个按钮)。

    您可以创建一个状态变量来管理索引。比如:

    this.state = {
        ...
        selectedIndex: 0
     }
    ...
    <ButtonGroup
       selectedIndex={this.state.selectedIndex}
       buttons={["First", "Second", "Third", "Fourth"]}
       containerStyle={{ height: 50 }}
       selectedButtonStyle={{ backgroundColor: "red" }}
       selectedTextStyle={{ color: "white" }}
       textStyle={{ fontSize: 18, fontWeight: '600' }}
       onPress={(selectedIndex) => {
          this.setState({ test: buttons[selectedIndex] });
          this.setState({ selectedIndex: selectedIndex });
       }}
    />
    

    【讨论】:

    • 您好!谢谢您的回答!我在那里试过,但我不知道应该把 this.state 部分放在哪里。我在 .tsx 文件中这样做
    • @Michael 与您定义 test 的部分完全相同。
    • 像魅力一样工作!非常感谢!
    • 很高兴听到这个消息。有一个很好的编码 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2021-10-28
    • 2019-03-12
    相关资源
    最近更新 更多