在 React Native ButtonGroup 中选择按钮

问题描述

我有一个小问题。我使用的 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]
        })}
      />

解决方法

发生这种情况是因为您设置了 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 });
   }}
/>
,

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

  this.state = {
   test: "First",btnIndex: 0
  }

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