Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
270 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 })
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...