简体   繁体   English

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

[英]Use inline style in React with plain CSS string

I am rewriting an existing App which was based on AngularJS in ReactJS.我正在重写一个基于 ReactJS 中的 AngularJS 的现有应用程序。 In the App the user has the possibility to provide a CSS style string to style certain elements.在应用程序中,用户可以提供 CSS 样式字符串来设置某些元素的样式。 In AngularJS this was no problem, I just set the 'style' attribute to the given string.在 AngularJS 中这没问题,我只是将 'style' 属性设置为给定的字符串。 In ReactJS I cannot do this anymore, because ReactJS requires a style object.在 ReactJS 中我不能再这样做了,因为 ReactJS 需要一个样式对象。 I do not want to change the behavior of the application and require users to now provide a ReactJS compatible style object.我不想改变应用程序的行为并要求用户现在提供兼容 ReactJS 的样式对象。 Is there any way in ReactJS to just use a plain CSS style string to set the style of an element? ReactJS 中是否有任何方法可以仅使用普通的 CSS 样式字符串来设置元素的样式?

You can set the style string with setAttribute('style', ...) in componentDidMount and componentDidUpdate .您可以在componentDidMountcomponentDidUpdate 中使用setAttribute('style', ...)设置样式字符串。

You just need to be able to get a reference to the DOM node that React created.你只需要能够获得对 React 创建的 DOM 节点的引用。 You can use refs for that.你可以使用refs

Here's an example.这是一个例子。 This component accepts a styleString prop, and sets it as the style on the <div/> that it renders.该组件接受一个styleString ,并将其设置为它呈现的<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;

Made a module that can handle this called Style It easy peasy, think we should all get back to simply writing CSS.制作了一个可以处理这种称为Style It easy peasy 的模块,认为我们都应该回到简单地编写 CSS。

Just pass in the style string as a prop.只需将样式字符串作为道具传递即可。

npm install style-it --save

Functional Syntax ( JSFIDDLE )函数式语法( JSFIDDLE )

import React from 'react';
import ReactDOM from 'react-dom';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return Style.it(
      this.props.cssText,
      <p className="intro">CSS-in-JS made simple -- just Style It.</p>
    );
  }
}

ReactDOM.render(
  <Intro cssText=".intro { color: red; }"/>,
  document.getElementById('container')
);

JSX Syntax ( JSFIDDLE ) JSX 语法( JSFIDDLE )

import React from 'react';
import ReactDOM from 'react-dom';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return (
      <Style>
      {this.props.cssText}

      <p className="intro">CSS-in-JS made simple -- just Style It.</p>
    </Style>
  }
}

export default Intro;

ReactDOM.render(
  <Intro cssText=".intro { color: red; }"/>,
  document.getElementById('container')
);

If you're using styled-components then don't even bother looking at the other answers.如果您正在使用styled-components那么甚至不必费心查看其他答案。 With v4 you can literally just pass a string to the css prop to any html tag or a styled component.使用 v4,您实际上可以将字符串传递给任何 html 标签或样式组件的 css prop。

<div css="margin-top: 4px;">
Yes it works just like that :).
</div>

And guess what you don't even need to import styled-components .猜猜你甚至不需要导入styled-components All you need to do is add this babel plugin.您需要做的就是添加这个babel 插件。 It turns any element with a css prop into a styled component.它将任何带有 css prop 的元素转换为样式化组件。

Read more here .在这里阅读更多。

This is a hack I found for reagent, but I believe it'll work equally well for raw react versions >= 16 (where custom dom attributes are passed threw).这是我为试剂发现的一个技巧,但我相信它对于原始反应版本 >= 16(自定义 dom 属性被抛出)同样有效。 Just use the upper case STYLE attribute instead of lower case style , which is intercepted by React.只需使用大写的STYLE属性而不是小写的style ,这是 React 拦截的。

Convert the style string to javascript object将样式字符串转换为 javascript 对象

this was the solution for me.这是我的解决方案。 I had a json object generated like this我有一个像这样生成的json对象

const generatedStyles = {
    "background-image": "url(\"http:/someurl/foo.JPEG\"), 
    "background-size": "auto 30px",
    "background-position": "center center"
}

I needed a method to convert this to a new object with camelCased keys for react-styles object.我需要一种方法将其转换为一个新对象,该对象带有用于 react-styles 对象的驼峰式键。 I have defined this in my component.我已经在我的组件中定义了这个。

renameKeys(obj) {
    const keyValues = Object.keys(obj).map(key => {
        var camelCased = key.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
        return { [camelCased]: obj[key] };
    });
    return Object.assign({}, ...keyValues);
}

and can be used in the render like <a style={this.renameKeys(generatedStyles)}>styled link</a>并且可以像<a style={this.renameKeys(generatedStyles)}>styled link</a>一样在渲染中使用

complementing taylor michels' answer补充泰勒米歇尔的回答

function CSSstring(string) {
  const css_json = `{"${string
    .replace(/; /g, '", "')
    .replace(/: /g, '": "')
    .replace(";", "")}"}`;

  const obj = JSON.parse(css_json);

  const keyValues = Object.keys(obj).map((key) => {
    var camelCased = key.replace(/-[a-z]/g, (g) => g[1].toUpperCase());
    return { [camelCased]: obj[key] };
  });
  return Object.assign({}, ...keyValues);
}


return <div style={CSSstring("margin-top: 4px; top: 100px")}></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM