我知道你可以在React类中指定样式,像这样:

const MyDiv = React.createClass({
  render: function() {
    const style = {
      color: 'white',
      fontSize: 200
    };
    
    return <div style={style}> Have a good and productive day! </div>;
  }
});

我应该瞄准这样做的所有样式,并没有在我的CSS文件中指定的样式吗?

或者我应该完全避免内联样式?

这似乎有点奇怪和混乱做一点两者-两个地方需要检查时调整样式。


当前回答

有时候,我们需要从组件中样式化一些元素,但如果我们必须只显示该组件的一个元素,或者样式是如此之少,那么我们不使用CSS类,而是在react js中使用内联样式。reactjs的内联样式和HTML的内联样式是一样的,只是属性名略有不同

使用style={{prop:"value"}}在任何标签中写入样式

import React, { Component } from "react";
    import { Redirect } from "react-router";

    class InlineStyle extends Component {
      constructor(props) {
        super(props);
        this.state = {};
      }

      render() {
        return (
          <div>
            <div>
              <div
                style={{
                  color: "red",
                  fontSize: 40,
                  background: "green"
                }}// this is inline style in reactjs
              >

              </div>
            </div>
          </div>
        );
      }
    }
    export default InlineStyle;

其他回答

JSX中的样式与HTML中的样式非常相似。

HTML的例子:

Div style="background-color: red;颜色:白色”

JSX案例:

div style={{backgroundColor: '红色',color: '白色'}}

我通常有与每个React组件相关联的scss文件。但是,我不明白为什么你不封装组件与逻辑,并查看它。我的意思是,你有类似的web组件。

我更喜欢使用样式化组件。为设计提供了较好的解决方案。

import React, { Component, Fragment } from 'react'
import styled from 'styled-components';

const StyledDiv = styled.div`
    display: block;
    margin-left: auto;
    margin-right: auto;
    font-size:200; // here we can set static
    color: ${props => props.color} // set dynamic color by props
`;

export default class RenderHtml extends Component {
    render() {
        return (
            <Fragment>
                <StyledDiv color={'white'}>
                    Have a good and productive day!
                </StyledDiv>
            </Fragment>
        )
    }
}

2020年更新:最好的做法是使用一个已经为你完成了艰苦工作的库,并且在你进行转换时不会杀死你的团队,正如本视频中最初接受的答案所指出的那样(它仍然相关)。为了了解趋势,这是一个非常有用的图表。在做了自己的研究之后,我选择在我的新项目中使用Emotion,它被证明是非常灵活和可扩展的。

鉴于2015年投票最多的答案是推荐镭,现在已经进入维护模式。因此,增加一些备选方案似乎是合理的。停止使用镭的帖子建议使用几个图书馆。每个链接的网站都有现成的示例,所以我将避免在这里复制和粘贴代码。

Emotion which is "inspired by" styled-components among others, uses styles in js and can be framework agnostic, but definitely promotes its React library. Emotion has been kept up to date as of this post. styled-components is comparable and offers many of the same features as Emotion. Also actively being maintained. Both Emotion and styled-components have similar syntax. It is built specifically to work with React components. JSS Yet another option for styles in js which is framework agnostic though it does have a number of framework packages, React-JSS among them.

style属性的主要用途是动态的、基于状态的样式。例如,您可以在进度条上基于某种状态设置宽度样式,或者基于其他内容设置位置或可见性。

JS中的样式限制了应用程序不能为可重用组件提供自定义样式。在前面提到的情况下,这是完全可以接受的,但当您更改可见特征时,尤其是颜色。