JonasLiu90
JonasLiu90
采纳率0%
2021-03-01 04:06

reactjs 怎样实现多个按钮中,每次点击其中任意一个按钮,只会改变其背景色?

10
已结题

各位大神好:

    我想用reactjs实现一个效果,在多个按钮中,每次点击其中任意一个按钮,只会改变其背景色。(效果图已上传,请参考

class Quesitons2 extends React.Component{
    state = {
        currentQuestion: {},
        active: false
    }

    selectQuesion = (question) => {
        this.setState({
            currentQuestion: question,
            active: true
        })
    }

    render(){
        const _class = {
            true: 'question active',
            false: 'question'
        }

        return(
            <div className="questions">
                <div className="columns is-multiline is-desktop ">
                    <div className="panel-container">
                        <Panel currentQuestion={this.state.currentQuestion}/>
                    </div>

                    {questions.map( q => {
                        return(
                            <button
                                className = {_class[this.state.active]}

                                key={q.id}
                                onClick={() => this.selectQuesion(q)}
                            >
                                {q.name}
                            </button>
                        )
                    })}
                </div>
            </div>
        )
    }
}

  • 点赞
  • 收藏
  • 复制链接分享

2条回答

  • weixin_41908433 知雀的天空 1月前
    class Quesitons2 extends React.Component{
        state = {
            currentQuestion: {},
            active: false
        }
     
        selectQuesion = (e, question) => {
                  e.stopPropagation();
                  e.target.style.background = 'red';
            this.setState({
                currentQuestion: question,
                active: true
            })
        }
     
        render(){
            const _class = {
                true: 'question active',
                false: 'question'
            }
     
            return(
                <div className="questions">
                    <div className="columns is-multiline is-desktop ">
                        <div className="panel-container">
                            <Panel currentQuestion={this.state.currentQuestion}/>
                        </div>
     
                        {questions.map( q => {
                            return(
                                <button
                                    key={q.id}
                                    onClick={e => this.selectQuesion(e, q)}
                                >
                                    {q.name}
                                </button>
                            )
                        })}
                    </div>
                </div>
            )
        }
    }

    e.stopPropagation(); // 阻止点击事件的冒泡
    e.target.style.background = 'red'; // 改变背景色

    点赞 评论 复制链接分享
  • JonasLiu90 JonasLiu90 1月前

    重新上传效果图

    点赞 评论 复制链接分享

为你推荐