单击时更改按钮图标反应 [英] change button icon on click react

查看:166
本文介绍了单击时更改按钮图标反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用react,我有一个带图标的按钮,一个字体太糟糕的按钮.我想在单击图标之间切换:该图标是带有标题和布尔值的眼睛.如果布尔值为true,则应睁大眼睛.如果单击同一按钮,则布尔值将变为false,并且按钮的图标应更改为关闭. 我的按钮已经过验证,因此如果布尔值为true或false,它将更改图标,我的问题在于更改布尔onClick.尝试使用setState无法做到这一点.

Using react, I have a button with an icon, a font-awsome one. I want to toggle between icon on click: the icon is an eye with a title and a boolean. If the boolean is true, the eye should be open. If the same button is clicked, the boolean turns false and the button's icon should change to close. My button already has a verification so it will change the icon if the boolean is true or false, my problem is on changing the boolean onClick. Tried with setState wasnt able to do so.

我的按钮:

   {props.eyes.map(eye => {
                    return (<div className={"column is-2"}>
                        <button
                            className={eye.toggled === 'true' ? "button is-white fa fa-eye" : "button is-white fa fa-eye-slash"}
                            onClick={() => props.pickEye(eye)}/>
                        {eye.tituloEye}
                    </div>)
                })}

我的状态:

state = {

            eyes:
                [
                    {
                        toggled: 'false',
                        tituloEye: 'porta'
                    },
                    {
                        toggled: 'true',
                        tituloEye: 'prateleira'
                    },
                ],

            eyeSelecionado: '',
}

我将获得如下单击按钮:

and Im getting the click button like:

pickEye = (eye) => {
    this.setState({eyeSelecionado: eye});
};

推荐答案

您需要在父状态下设置切换后的值,例如

You need to set the toggled value in the parent state like

    {props.eyes.map((eye, index) => {
        return (<div className={"column is-2"}>
            <button
                className={eye.toggled === true 
                    ? "button is-white fa fa-ye" 
                    : "button is-white fa fa-eye-slash"
                }
                onClick={() => props.pickEye(index)}
            />
                {eye.tituloEye}
            </div>
        )
    }
)}

pickEye = (index) => {
    this.setState(prevState => ({
        var newState = {
            [index]: {
                ...prevState.eyes[index], 
                toggled: !prevState.eyes[index].toggled
            }
        };
        eyes: Object.assign([], prevState.eyes, newState)}));
};

这篇关于单击时更改按钮图标反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆