如何在ReactJS中使用refs来更改样式类
How I can use refs to change styling class in ReactJS?
当颜色值改变时,我试图改变div
的背景。下面是我接收颜色值的函数:
ChangeColor(oColor) {
this.props.ChangeColor(oColor);
console.log("Refs: ", this.refs.colorPicker.className);
},
这里是css类
.colorPicker {
padding-right: 25px;
background: #000;
display: inline;
margin-right: 5px;
}
这是我的div元素,它的背景需要在运行时更新。
<div ref='colorPicker' className={this.GetClass("colorPicker")} />
我不确定refs语法,所以请帮助解决这个问题。谢谢。
我找到了。下面是答案:
ChangeColor(oColor) {
this.props.ChangeColor(oColor);
this.refs.colorPicker.style.background = oColor; //this is how background will be updated
},
如果有人在寻找hooks版本
export const YourComponent = (props) => {
const divRef: = useRef(null);
yourTriggerEvent = () => {
divRef.current.style.background = 'red';
}
return (
<div ref={divRef}>
</div>
);
}
也可以用ref元素改变div的颜色。例如:
const myReference = this.colorPicker.current // The DOM element
myReference.style.backgroundColor = "red"; // The style you want to apply
相关文章:
- 当包含另一个asp文件时,是否也包含所有引用的样式和脚本页面
- 将样式表插入iframe
- 跟踪在页面加载时应用内联样式的JavaScript
- 如果文本字段为空,则使用JavaScript应用CSS样式
- 定义完全独立的样式信息
- W3C循环样式的JavaScript
- jQuery/JavaScript在线公文包表单-打印样式表
- 使用递归、Ramda.js和无点样式重构字符串的getPermutations()
- FF和Chromium中CSS样式按钮的外观差异
- reactjs this.refs vs document.getElementById
- 如何首先设置样式<td>表中包含在窗体中的元素
- javascript问题正文样式
- 使用具有内联样式的tidy-html5
- DataTables-创建自定义分页样式(加载更多样式)
- 具有所有样式的文本正在复制到可编辑文本区域
- 如何提供在javascript中编写对对象的重复访问以设置元素样式的简写
- 绑定Range输入以修改样式
- 一个正则表达式,用于从JS中的HTML标记中删除id、样式和类属性
- 不同页面背景的body标记上的角度ng样式
- 如何在ReactJS中使用refs来更改样式类