有没有办法从回调函数onPress更改Button样式的透明度

时间:2018-06-27 15:05:17

标签: reactjs react-native react-native-android

enter image description here

我是React Native的新手,我试图使Button被选中,而其他按钮未被选中,因此在Web中,我从所有按钮中删除了所有选中的类,然后将该类提供给所选的一个

我该怎么办?

2 个答案:

答案 0 :(得分:0)

对于您的问题,解决此问题的一种方法是在组件构造函数中保持如下状态:this.state={selected: 0}。状态selected的整数将是同一容器中按钮中当前按下的按钮的索引。

假设您使用类似的东西来映射按钮

buttons.map((button, index) => 
<Button>
 <Text>
  Some Text
 </Text>
</Button>)

您应该能够在每个key标签中附加一个Buttonindex。然后,您可以在每个Button中调用一个组件方法,该方法利用key将状态的selected设置为被按下按钮的index。最后,您可以通过检查状态值来基于当前选择的按钮呈现不同的样式。

答案 1 :(得分:0)

import React, { Component } from 'react'
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Button
} from 'react-native'


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {buttonClick: false};
  }
  onClickButton() {
    this.setState(previousState => {
        return {buttonClick: !previousState.buttonClick};
      });
  }
  render() {
    const cssButtonStyle = (this.state.buttonClick)? 'darkslateblue' : 'mediumturquoise';
    console.log(this.state.buttonClick);
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Button
        color={cssButtonStyle}
        onPress={(event) => this.onClickButton(event)}
        title="Learn More"
        accessibilityLabel="Learn more about this purple button"
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
})

AppRegistry.registerComponent('App', () => App)

这是使用React-Native实际上可以实现的。 它仅具有基本的自定义。(https://facebook.github.io/react-native/docs/button)。

在此位置使用上面的代码: http://dabbott.github.io/react-native-web-player/

您可以使用此npm包进行更多自定义: https://github.com/ide/react-native-button