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

Jan*_*fer 3 javascript css reactjs

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

ray*_*bbs 8

这是我为reagent找到的一个hack,但我相信它对于原始react版本> = 16(其中自定义dom属性被传递抛出)同样有效。只需使用大写STYLE属性而不是小写属性style,它会被 React 拦截。


Pra*_*ana 6

如果您正在使用styled-components,那么甚至不必费心查看其他答案。使用 v4,您实际上可以将字符串传递给 css prop 到任何 html 标签或样式化组件。

<div css="margin-top: 4px;">
Yes it works just like that :).
</div>
Run Code Online (Sandbox Code Playgroud)

猜猜你甚至不需要导入什么styled-components。您需要做的就是添加这个babel 插件。它将任何带有 css prop 的元素转换为样式组件。

在这里阅读更多内容。


And*_*rew 5

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

您只需要能够获得React创建的DOM节点的引用.你可以使用refs.

这是一个例子.此组件接受styleStringprop,并将其设置为<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;
Run Code Online (Sandbox Code Playgroud)