小编app*_*_92的帖子

如何在多个按钮React Native中更改按下的颜色按钮

我的反应原生应用程序中有3个按钮.当用户单击按钮1时,我需要将其颜色更改为橙​​色.但其他按钮应具有默认颜色(灰色).如果用户下次单击按钮3,颜色应更改为橙色,但第一个按钮颜色应重置为默认值.我对原生的反应是全新的,这就是我的尝试.但它适用于所有按钮.我知道如果我可以拥有具有唯一ID的多个状态,则可以完成.但我不知道这个方法.

<Text style={ styles.switchButtonsTitle }>Choose Type of User</Text>
<TouchableOpacity onPress={(userType) =>
    this.selectionOnPress("BASIC")} >
    <Text style={_style}>
        <Text style={styles.switchButtonsText}>BASIC</Text>
    </Text>
</TouchableOpacity>


<TouchableOpacity onPress={(userType) =>
    this.selectionOnPress("INTERMEDIATE")}>
    <Text style={_style}>
        <Text style={styles.switchButtonsText}>INTERMEDIATE</Text>
    </Text>
</TouchableOpacity>

<TouchableOpacity onPress={(userType) =>
    this.selectionOnPress("ADVANCED")}>
    <Text style={{backgroundColor: this.state.backgroundColor}}>
        <Text style={styles.switchButtonsText}>ADVANCED</Text>
    </Text>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)

selectionOnPress

selectionOnPress(userType) {
    this.setState({
        onClicked: true
    });
} 
Run Code Online (Sandbox Code Playgroud)

道具

constructor(props) {
    super(props);
    this.state = {
        onClicked: false
    }
    this.selectionOnPress = this.selectionOnPress.bind(this)
}
Run Code Online (Sandbox Code Playgroud)

渲染(不添加所有代码,只添加了这篇文章的有用代码)

render() {
    var _style;
    if (this.state.onClicked) { // clicked button style
        _style = {
            backgroundColor: "red"
        } …
Run Code Online (Sandbox Code Playgroud)

javascript react-native

4
推荐指数
1
解决办法
5228
查看次数

标签 统计

javascript ×1

react-native ×1