0

尝试使用 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 控制台为所有样式返回空值。

我正在使用 react-css-modules/css-modules,这是我能想到的唯一异常。

任何想法都非常受欢迎,谢谢。

编辑:我专门为这个 stackoverflow 问题创建了一个分支:https ://github.com/CharlieGreenman/pixelLight/tree/stackoverflow-37583025

注意:这个应用程序的数据流是有一个静态值,它填充应用程序的其余部分是动态的。作为对建议的回应,经过深思熟虑,我决定这是构建应用程序的正确方法。

4

2 回答 2

1

最后,我用

const backgroundStyle = window.getComputedStyle(e.target, null).getPropertyValue("background-color");

这让我得到了正确的价值。我认为这是由于在这个应用程序中发生了两件事。

  1. 样式标签被直接注入到 html 中。如果它是 webpack-dev-server 或 react-css-modules 的结果,则不是 100%。
  2. 样式仅在 react 应用程序初始化后应用,并应用了适当的设置。

因此,在这种情况下,获得计算样式对我来说就是这样做的。我仍在研究特定的细节。谢谢你。

于 2016-06-05T18:20:00.147 回答
0

您可以使用 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);
}
于 2016-06-02T05:12:39.790 回答