更改自定义单选按钮图像onclick

时间:2019-05-07 02:43:35

标签: react-native

我试图创建一个可以在单击时更改图像的按钮,现在尝试更改图像的不透明度。这是我对自定义按钮所做的

const styles = StyleSheet.create({
    container: {
        marginVertical: normalize(5),
        opacity: 0.5
    },

    activeButton: {
        opacity: 1
    }
});

export default class RadioButton extends Component {
    constructor(props) {
        super(props);

        this.state = {
            selected: this.props.currentSelection === this.props.value,
        }
    }

    componentDidUpdate(prevProps) {
        if (this.props.currentSelection !== prevProps.currentSelection) {
            this.setState({ selected: this.props.currentSelection === this.props.value });
        }
    }

    render() {
        let activeButton = this.props.activeStyle ? this.props.activeStyle : styles.activeButton;

        return (
            <View style={[styles.container, this.props.containerStyle, this.state.selected ? activeButton : null]}>
                <TouchableOpacity onPress={() => {
                    this.setState({ selected: !this.state.selected });
                    this.props.onPress();
                }}>
                    {
                        this.props.element ?
                            this.props.element :
                            <Text> {this.props.value} </Text>
                    }
                </TouchableOpacity>
            </View>

        );
    }
}

应该是这样的image

1 个答案:

答案 0 :(得分:0)

首先导入两个图像。一个用于选定状态,另一个用于正常状态。

select * from roles;
id | role_name | user_type | inserted_at | updated_at
----±----------±----------±--------------------±--------------------
1 | SUPER | | 2019-05-06 09:37:30 | 2019-05-06 09:37:30

然后将以下方法添加到您的组件

import selectedImg from '../images/selected.png';
import normalImg from '../images/normal.png';

现在按如下所示编辑渲染方法

btnBackgroundImage() = {
    var imgSource = this.state.selected? selectedImg : normalImg;
    return (
      <Image
        style={'put style here'}
        source={ imgSource }
      />
    );
  }
相关问题