首页 > 解决方案 > 如何在本机反应中突出显示单个按钮?

问题描述

如何突出显示被多个按钮包围的单个按钮?

这是我呈现按钮的组件。另外,我导入了一个我不久前创建的自定义按钮。

 const button = [
    {
        title: '#Food',
        selected: false,
        id: 1
    },
    {
        title: '#Fashion',
        selected: false,
        id: 2
    },
    {
        title: '#Art',
        selected: false,
        id: 3
    }]

 {button.map(({ title, id, selected }) => {
                return (
                    <View style={{ width: '25%', padding: 5, }}>
                        <CustomButton
                            bgColor={active ? 'red' : 'blue'}
                            title={title}
                            key={id}
                            onPress={() => chosenButton(selected, id)}
                            textColor={Colors.PRIMARY_COLOR} />
                    </View>
                )
            })}

这是我的自定义按钮

    const CustomButton = ({ title, containerStyle, textStyle, bgColor, textColor, onPress }) => {
    return (
        <Button onPress={onPress} block rounded style={[styles.btnStyle, containerStyle, { backgroundColor: bgColor, }]}>
            <Text style={[styles.text, textStyle, { color: textColor }]}>{title}</Text>
        </Button>
    );
};

截至目前,这是我的按钮

图片

但是我想突出显示一个按钮并在单击时更改它的背景颜色。我怎样才能做到这一点?

标签: javascriptreactjsreact-nativejsx

解决方案


您可以useState在子组件中执行并在单击时更改颜色

 const CustomButton = ({ title, containerStyle, textStyle, bgColor, textColor, onPress }) => {
    const [bgCol,setBgCol] = useState(bgColor);
    const changeBg = () => setBgCol('yellow');

    return (
        <Button onPress={()=>{changeBg();onPress()}} block rounded style={[styles.btnStyle, containerStyle, { backgroundColor: bgCol, }]}>
            <Text style={[styles.text, textStyle, { color: textColor }]}>{title}</Text>
        </Button>
    );
};

推荐阅读