我知道你可以在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文件,特别是包含该组件的所有样式选项(并且仅针对该组件)。

var MyDiv = React.createClass({
  render: function() {
    return <custom-component style={style}> Have a good and productive day! </custom-component>;
  }
});

在文件'custom-component.css'中,每个条目都以custom-component标签开始:

custom-component { 
   display: block; /* have it work as a div */
   color: 'white'; 
   fontSize: 200; 
} 
custom-component h1 { 
  font-size: 1.4em; 
}

这意味着你不会失去关注点分离的关键概念。视图与样式。如果你共享你的组件,其他人更容易将其主题化以匹配他们网页的其余部分。

其他回答

TLDR -使用css在js解决方案(如情感或样式组件),享受最好的css和js所提供的

在css或scss文件中,很难管理动态样式。在内联样式标签中,不能使用媒体查询或伪选择器。

在JS中使用CSS,你可以享受两全其美。JS中的Css之于Css有点像React之于HTML。它允许在JS代码中以对象或字符串的形式编写css,并享受javascript生态系统的强大功能和工具。

到目前为止,js库中有一些受欢迎的、得到良好支持的CSS,包括Emotion、styles - components和镭。


让我们比较一下样式化简单元素时代码的样子。我们将设置“hello world”div的样式,这样它在桌面上显示大,在移动端显示小。

使用style属性

return (
   <div style={{fontSize:24}} className="hello-world">
      Hello world
   </div>
)

由于媒体查询在样式标签中是不可能的,我们必须向元素中添加一个className并添加一个css规则。

@media screen and (max-width: 700px){
   .hello-world {
      font-size: 16px; 
   }
}

使用Emotion的10 CSS标签

return (
   <div
      css={{
         fontSize: 24, 
         [CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY]:{
            fontSize: 16 
         }
      }
   >
      Hello world
   </div>
)

Emotion还支持模板字符串和样式化组件。所以如果你喜欢,你可以这样写:

return (
   <Box>
      Hello world
   </Box>
)

const Box = styled.div`
   font-size: 24px; 
   ${CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY}{
      font-size: 16px; 
   }
`

“JS中的CSS”背后使用的是CSS类。

最佳实践

以下是我推荐的一些最佳实践:

在JS中使用CSS解决方案 在JS中构造样式代码与构造一般的代码非常相似。例如:

识别重复的样式,并将它们写在一个地方。在Emotion中有两种方法:

// option 1 - Write common styles in CONSTANT variables
// styles.js
export const COMMON_STYLES = {
   BUTTON: css`
      background-color: blue; 
      color: white; 
      :hover {
         background-color: dark-blue; 
      }
   `
}

// SomeButton.js
const SomeButton = (props) => {
   ...
   return (
      <button
         css={COMMON_STYLES.BUTTON}
         ...
      >
         Click Me
      </button>
   )
}

// Option 2 - Write your common styles in a dedicated component 

const Button = styled.button`
   background-color: blue; 
   color: white; 
   :hover {
      background-color: dark-blue; 
   }   
`

const SomeButton = (props) => {
   ...
   return (
      <Button ...> 
         Click me
      </Button>
   )
}

React编码模式是封装组件- HTML和JS,控制组件被写在一个文件中。这是你的css/样式代码样式的组件属于。 必要时,为组件添加样式道具。通过这种方式,您可以重用在子组件中编写的代码和样式,并通过父组件对其进行定制以满足您的特定需求。

const Button = styled.button([COMMON_STYLES.BUTTON, props=>props.stl])

const SmallButton = (props)=>(
   <Button 
      ...
      stl={css`font-size: 12px`}
   >
      Click me if you can see me
   </Button>
)

const BigButton = (props) => (
   <Button
      ...
      stl={css`font-size: 30px;`}
   >
      Click me
   </Button>
)

下面是JSX语法中基于布尔的样式:

style={{display: this.state.isShowing ? "inherit" : "none"}}

有时候,我们需要从组件中样式化一些元素,但如果我们必须只显示该组件的一个元素,或者样式是如此之少,那么我们不使用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;

对于某些组件,使用内联样式更容易。此外,我发现它更容易和更简洁(因为我使用Javascript而不是CSS)动画组件样式。

对于独立组件,我使用“扩展操作符”或“…”。对我来说,它清晰、美丽,在狭小的空间里也能工作。下面是我制作的一个加载动画来展示它的好处:

<div style={{...this.styles.container, ...this.state.opacity}}>
    <div style={{...this.state.colors[0], ...this.styles.block}}/>
    <div style={{...this.state.colors[1], ...this.styles.block}}/>
    <div style={{...this.state.colors[2], ...this.styles.block}}/>
    <div style={{...this.state.colors[7], ...this.styles.block}}/>
    <div style={{...this.styles.block}}/>
    <div style={{...this.state.colors[3], ...this.styles.block}}/>
    <div style={{...this.state.colors[6], ...this.styles.block}}/>
    <div style={{...this.state.colors[5], ...this.styles.block}}/>
    <div style={{...this.state.colors[4], ...this.styles.block}}/>
  </div>

    this.styles = {
  container: {
    'display': 'flex',
    'flexDirection': 'row',
    'justifyContent': 'center',
    'alignItems': 'center',
    'flexWrap': 'wrap',
    'width': 21,
    'height': 21,
    'borderRadius': '50%'
  },
  block: {
    'width': 7,
    'height': 7,
    'borderRadius': '50%',
  }
}
this.state = {
  colors: [
    { backgroundColor: 'red'},
    { backgroundColor: 'blue'},
    { backgroundColor: 'yellow'},
    { backgroundColor: 'green'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
  ],
  opacity: {
    'opacity': 0
  }
}

2019年11月

在这个行业(一家财富500强公司)工作,我不允许做任何内联样式。在我们的团队中,我们认为内联样式是不可读和不可维护的。而且,在亲眼看到内联样式如何使支持应用程序变得完全无法忍受之后,我不得不同意这一点。我完全反对内联样式。

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

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>
        )
    }
}