React JS - 在点击时改变颜色,并在所有其他颜色上设置默认颜色 [英] React JS - Change color on click and put defaul color on all other ones

查看:3337
本文介绍了React JS - 在点击时改变颜色,并在所有其他颜色上设置默认颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

class =snippetdata-lang =jsdata-hide =falsedata-console =truedata-babel =true>

 < div className =wrapper> < div className =flex-grid> {object.keys(images).map((index,i)=> {return(< ArticlePreview onClick = {(evt)=> this.props.clicked(evt,i)} img = {images [index ]}} title = {titles [index]} description = {descriptions [index]} key = {i}>< / ArticlePreview>)})}< / div>< / div>  

当点击它时,我可以从特定组件改变div的颜色。

articleClicked =(evt,i)=> {evt.currentTarget.style.backgroundColor ='white'; }



但是,当我点击另一个组件时,previois的颜色被点击如果点击另一个组件,我希望它将其更改为默认值。

解决方案

更好的方法来使用React道具和状态。

必须将Click Handler函数传递给 div ,因为 onClick 道具适用于 DOM元素 React.Component 。



这是我的示例,它与@ Dev's相似



您可以参考 https://reactjs.org/docs/handling-events.html 获取更多信息。


I have "x" number of rendered ArticlePreview components that depends of API call.

<div className="wrapper">
  <div className="flex-grid">
    { Object.keys(images).map((index, i) => { return (
    <ArticlePreview onClick={(evt)=>this.props.clicked(evt, i)} img={images[index]} title={titles[index]} description={descriptions[index]} key={i}> </ArticlePreview>) }) }
  </div>
</div>

I can change color of div from specific component when I click on it.

articleClicked =(evt, i) => { evt.currentTarget.style.backgroundColor = 'white'; }

But whet I click to another component, color of previois clicked stays as clicked and I want it to change it to default value if I click another component.

解决方案

As Dev's Answer it is a better way to use React props and state.

It is necessary to pass the click Handler function to div because onClick props works on DOM elements but React.Component.

This is my example and it is similar with @Dev's

You can refer to https://reactjs.org/docs/handling-events.html for more info.

这篇关于React JS - 在点击时改变颜色,并在所有其他颜色上设置默认颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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