ReactJs向按钮添加活动类 [英] ReactJs adding active class to button

查看:69
本文介绍了ReactJs向按钮添加活动类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有五个动态创建的按钮。我的目标是:单击任何按钮以向其中添加活动类,当然,如果其他任何人有要删除的活动类。我该如何实现?

I have five buttons, dynamically created. My target is: when any button is clicked to add active class to it, and of course if any other has that active class to remove it. How can I achieve that?

<div>
    {buttons.map(function (name, index) {
        return <input type="button" value={name} onClick={someFunct} key={ name }/>;
   })}
</div>


推荐答案

您需要将状态引入组件并进行设置在 onClick 事件处理程序中。例如渲染方法的输出:

You need to introduce state to your component and set it in onClick event handler. For example output of render method:

<div>
    {buttons.map(function (name, index) {
        return <input
                 type="button"
                 className={this.state.active === name ? 'active' : ''}
                 value={name}
                 onClick={() => this.someFunct(name)}
                 key={ name } />;
   })}
</div>

事件处理程序(元素方法):

event handler (element method):

someFunct(name) {
    this.setState({ active: name })
}

这篇关于ReactJs向按钮添加活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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