Muh*_*zam 11 javascript css refs reactjs css-modules
我正在尝试更改div颜色值更改时的背景.这是我的函数,它接收颜色值:
ChangeColor(oColor) {
this.props.ChangeColor(oColor);
console.log("Refs: ", this.refs.colorPicker.className);
},
Run Code Online (Sandbox Code Playgroud)
这是css类
.colorPicker {
padding-right: 25px;
background: #000;
display: inline;
margin-right: 5px;
}
Run Code Online (Sandbox Code Playgroud)
这是我的div元素,其背景需要在运行时更新.
<div ref='colorPicker' className={this.GetClass("colorPicker")} />
Run Code Online (Sandbox Code Playgroud)
我不确定refs synatx所以请帮助解决这个问题.谢谢.
Muh*_*zam 18
我找到了.这是答案:
ChangeColor(oColor) {
this.props.ChangeColor(oColor);
this.refs.colorPicker.style.background = oColor; //this is how background will be updated
},
Run Code Online (Sandbox Code Playgroud)
Jon*_*ero 10
如果有人正在寻找 hooks 版本
export const YourComponent = (props) => {
const divRef: = useRef(null);
yourTriggerEvent = () => {
divRef.current.style.background = 'red';
}
return (
<div ref={divRef}>
</div>
);
}Run Code Online (Sandbox Code Playgroud)
小智 5
此外,您可以使用 ref 元素更改 div 的颜色。例如:
const myReference = this.colorPicker.current // The DOM element
myReference.style.backgroundColor = "red"; // The style you want to apply
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16175 次 |
| 最近记录: |