我在ReactJS项目中有一个div元素列表。我只想在有人单击时指示更改背景颜色。
以下是基本代码。
function changetoselected(event){
// now change backgroundColor of
// event.currentTarget to white
}
<div>
bigarrayofsize100plus.map((item,index) =>{
return(
<div
className="p-2"
onClick={(e) => changetoselected(e)}
style={{backgroundColor:"green"}}
>
.....
</div>
)
}
</div>
我不想在状态中不必要地存储所有要素。我不必在这里跟踪单击的项目。
如果单击一次,我只想更改颜色。我该怎么做
使用style属性设置这样的backgroundColor。
function changetoSelected(event){
event.target.style.backgroundColor = '#fff'
}
您也可以像这样在React中使用Refs
对于功能组件,请执行`
import { useRef } from 'react';
function MyComponent() {
const divEl = useRef(null);
const changeToSelected = () => {
divEl.current.style.backgroundColor = '#fff';
};
return (
<div ref={divEl} onClick={changeToSelected}>
...
</div>
);
}
对于类组件,请执行此操作
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.divElement = React.createRef();
}
changetoselected = () => {
this.divElement.current.style.backgroundColor = '#fff';
}
render() {
return <div ref={this.divElement} onClick={this.changetoselected}>
...
</div>;
}
}
毕竟,使用纯dom(通过ref或event)可能不是您要搜索的内容,您可以考虑使用react state并将className或style应用于dom元素
import { useState } from 'react';
const MyComponent = () => {
const [backgroundColor, setBackgroundColor] = useState('green');
return (
<div
onClick={() => setBackgroundColor('white')}
style={{ backgroundColor }}
>
...
</div>
);
}
编辑
function MyComponent() {
const divEl = useRef(null);
const changeToSelected = () => {
divEl.current.style.backgroundColor = '#fff';
};
return (
<div>
{bigarrayofsize100plus.map((item,index) =>
<ChildComp
key={index}
item={item}
>
.....
</div>
)}
</div>
);
}
function ChildComp({ item }) {
const divEl = useRef(null);
const changeToSelected = () => {
divEl.current.style.backgroundColor = '#fff';
};
return (
<div
ref={divEl}
onClick={changeToSelected}
className="p-2"
style={{backgroundColor:"green"}}
>
// do stuff with item heere
</div>
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句