javascript - 在 React 中使用纯 CSS 字符串使用内联样式

标签 javascript css reactjs

我正在重写一个基于 ReactJS 中的 AngularJS 的现有应用程序。在应用程序中,用户可以提供 CSS 样式字符串来设置某些元素的样式。在 AngularJS 中这没有问题,我只是将“style”属性设置为给定的字符串。在 ReactJS 中我不能再这样做了,因为 ReactJS 需要一个样式对象。我不想改变应用程序的行为并要求用户现在提供一个 ReactJS 兼容的样式对象。在 ReactJS 中有什么方法可以只使用纯 CSS 样式字符串来设置元素的样式吗?

最佳答案

您可以使用 setAttribute('style', ...) 设置样式字符串在 componentDidMountcomponentDidUpdate .

您只需要能够获得对 React 创建的 DOM 节点的引用。您可以使用 refs为此。

这是一个例子。该组件接受 styleString prop,并将其设置为 <div/> 上的样式它呈现。

import React from 'react';

class StyledDiv extends React.Component {
  componentDidMount() {
    this.refs.theDiv.setAttribute('style', this.props.styleString);
  }

  componentDidUpdate() {
    this.refs.theDiv.setAttribute('style', this.props.styleString);
  }

  render() {
    return (
      <div ref="theDiv" />
    );
  }
}
StyledDiv.propTypes = {
  styleString: React.PropTypes.string,
};
export default StyledDiv;

关于javascript - 在 React 中使用纯 CSS 字符串使用内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33331570/

相关文章:

javascript - xPages 单选按钮组 onchange 事件不起作用

html - 悬停时更改选择列表选项的背景颜色

html - 悬停时增加 div 的高度但仅使用 CSS ...为什么?

html - css 跨表列垂直旋转文本

javascript - React Redux 元素未更新

javascript - 使用 react-router-dom v6 路由到新页面时,React 组件不呈现

javascript - 如果 finally 总是被执行,为什么 try 返回未更改的值

javascript - 使用 Math 的方法扩展窗口对象

javascript - 根据 js 脚本输出更改产品价格

javascript - 如何模拟 jest/enzyme 测试的 css 导入?