1

问题很简单,我想,但我似乎无法弄清楚。我正在使用react-native-router-flux库和NativeBase库作为按钮。React-Native:如何更改背景第二个动作

这是我的代码:

<Button transparent onPress={Actions.MainOne } style={{ width: 50, height: 50 }} > 
     <Text>Option1</Text> 
    </Button> 

    <Button transparent onPress={Actions.MainTwo} style={{ width: 50, height: 50 }} > 
      <Text>Option2</Text> 
    </Button> 

我想改变每当我按下按钮的背景颜色和它的活跃。如果我点击另一个按钮,那么我刚刚按下的按钮将获得背景,并且第一个按钮会返回到正常的透明背景。我不确定我可以如何将两个动作添加到按钮。如果任何人都可以协助,我将不胜感激。我不需要使用按钮库,所以对此有任何想法都是值得欢迎的!

谢谢!

回答

0

我使用flux-router来浏览场景。这是我如何在按下时更改按钮的背景颜色:

constructor() { 
     super(); 
     state = { 
     color1: 'transparent', 
     color2: 'transparent', 
     } 
    } 

    setActive(button) { 
     if (button === 1) { 
     if (this.state.color1 === 'transparent') { 
      this.setState({ 
      color1: 'red', 
      color2: 'transparent' 
      }) 
     } 
     } else { 
     if (this.state.color2 === 'transparent') { 
      this.setState({ 
      color2: 'red', 
      color1: 'transparent' 
      }) 
     } 
     } 
    } 

    { . . . } 

    <Button 
     onPress={this.setActive.bind(this, 1)} 
     style={{ width: 50, height: 50, backgroundColor: this.state.color1 }} 
    > 
     <Text>Option1</Text> 
    </Button> 

    <Button 
     this.setActive.bind(this, 2) 
     style={{ width: 50, height: 50, backgroundColor: this.state.color2 }} 
    > 
     <Text>Option2</Text> 
    </Button>