在 React 中获取目标 html 元素的颜色
Get color of target html element in React
尝试使用 React 获取 html 元素的颜色,以传递给我的 redux action/reducer。
JSX
<div>
<button styleName="css_toggle" id ="css" onClick {this.handleClick}>CSS</button>
</div>
事件处理器
handleClick(e){
const{dispatch} = this.props;
console.log(`e.target: ${e.target.style}`);
dispatch(CurrView(e.target.id, e.target.style.background));
}
Console/redux 控制台 returns 所有样式的空值。
我正在使用 react-css-modules/css-modules,这是我能想到的唯一异常情况。
非常欢迎任何想法,谢谢。
编辑:我专门为这个 Whosebug 问题创建了一个分支:https://github.com/CharlieGreenman/pixelLight/tree/Whosebug-37583025
注意:此应用的数据流是单个静态值,该值填充动态应用的其余部分。作为对建议的回应,经过深思熟虑,我决定这是构建应用程序的正确方法。
您可以使用 refs 可靠地引用元素。
JSX
<div>
<button id ="css"
styleName="css_toggle"
onClick={this.handleClick}
ref={(e) => { this.cssToggleButton = e; }}>
CSS
</button>
</div>
事件处理程序
handleClick() {
const id = this.cssToggleButton.id;
const background = this.cssToggleButton.style.background;
this.props.dispatch(id, background);
}
最后,我用了
const backgroundStyle = window.getComputedStyle(e.target, null).getPropertyValue("background-color");
这让我获得了正确的价值。我认为这是此应用程序中发生的两件事的结果。
- 样式标签直接注入 html。如果是 webpack-dev-server 或 react-css-modules.
的结果,则不是 100%
- 仅在 React 应用程序初始化后应用样式,并应用适当的设置。
就是这样,在这种情况下,获取计算样式对我来说是有用的。我仍在研究特定细节。谢谢你。
尝试使用 React 获取 html 元素的颜色,以传递给我的 redux action/reducer。
JSX
<div>
<button styleName="css_toggle" id ="css" onClick {this.handleClick}>CSS</button>
</div>
事件处理器
handleClick(e){
const{dispatch} = this.props;
console.log(`e.target: ${e.target.style}`);
dispatch(CurrView(e.target.id, e.target.style.background));
}
Console/redux 控制台 returns 所有样式的空值。
我正在使用 react-css-modules/css-modules,这是我能想到的唯一异常情况。
非常欢迎任何想法,谢谢。
编辑:我专门为这个 Whosebug 问题创建了一个分支:https://github.com/CharlieGreenman/pixelLight/tree/Whosebug-37583025
注意:此应用的数据流是单个静态值,该值填充动态应用的其余部分。作为对建议的回应,经过深思熟虑,我决定这是构建应用程序的正确方法。
您可以使用 refs 可靠地引用元素。
JSX
<div>
<button id ="css"
styleName="css_toggle"
onClick={this.handleClick}
ref={(e) => { this.cssToggleButton = e; }}>
CSS
</button>
</div>
事件处理程序
handleClick() {
const id = this.cssToggleButton.id;
const background = this.cssToggleButton.style.background;
this.props.dispatch(id, background);
}
最后,我用了
const backgroundStyle = window.getComputedStyle(e.target, null).getPropertyValue("background-color");
这让我获得了正确的价值。我认为这是此应用程序中发生的两件事的结果。
- 样式标签直接注入 html。如果是 webpack-dev-server 或 react-css-modules. 的结果,则不是 100%
- 仅在 React 应用程序初始化后应用样式,并应用适当的设置。
就是这样,在这种情况下,获取计算样式对我来说是有用的。我仍在研究特定细节。谢谢你。