渲染需要服务器样式的React组件

时间:2015-03-26 15:29:09

标签: javascript css node.js reactjs webpack

我有需要里面样式的React.js组件:

import './styles.css
import React from 'react';

export default class Basket extends React.Component {
    ...
}

现在我想让我的应用程序同构并在服务器上预呈现它..

Babel开始抱怨css个文件并不奇怪:

SyntaxError: /Users/dmitri/github/app/src/client/pages/styles.css: Unexpected token (3:5)
  2 |
> 3 | body {
    |      ^
  4 |     background-color: #ddd;
  5 | }
  6 |

如何让它发挥作用?对node-jsx - https://github.com/petehunt/node-jsx/issues/29

进行了类似的讨论

我应该为此导入添加if (browser)语句吗?

2 个答案:

答案 0 :(得分:0)

这是一种不同的方法,但请查看Radium。您可以将样式声明为JS对象,因此服务器不必知道或关心css是什么。

Radium页面的示例:

var React = require('react');
var Radium = require('radium');
var color = require('color');

var Button = React.createClass(Radium.wrap({
  displayName: "Button",

  propTypes: {
    kind: React.PropTypes.oneOf(['primary', 'warning']).isRequired
  },

  render: function () {
    // Radium extends the style attribute to accept an array. It will merge
    // the styles in order. We use this feature here to apply the primary
    // or warning styles depending on the value of the `kind` prop. Since its
    // all just JavaScript, you can use whatever logic you want to decide which
    // styles are applied (props, state, context, etc).
    return (
      <button
        style={[
          styles.base,
          styles[this.props.kind]
        ]}>
        {this.props.children}
      </button>
    );
  }
}));

// You can create your style objects dynamically or share them for
// every instance of the component.
var styles = {
  base: {
    padding: '1.5em 2em',
    border: 0,
    borderRadius: 4,
    color: '#fff',
    cursor: 'pointer',
    fontSize: 16,
    fontWeight: 700,

    // Adding interactive state couldn't be easier! Add a special key to your
    // style object (:hover, :focus, :active, or @media) with the additional rules.
    ':hover': {
      background: color('#0074d9').lighten(0.2).hexString()
    },

    // If you specify more than one, later ones will override earlier ones.
    ':focus': {
      boxShadow: '0 0 0 3px #eee, 0 0 0 6px #0074D9',
      outline: 'none'
    },
  },

  primary: {
    background: '#0074D9'
  },

  warning: {
    background: '#FF4136'
  }
};

请记住,如果您不是内联css的粉丝,您可以随时在单独的JS中定义样式并导入它们。

答案 1 :(得分:0)

我和你有完全相同的需求。我使用 webpack 打包我的应用。在webpack中,您可以定义几个变量,如下所示:

var define = new webpack.DefinePlugin({
    "process.env": {
        BROWSER: JSON.stringify(true)
    }
});

在我的jsx文件中:

if (process.env.BROWSER) {
    require('my-css');
}

我认为,还有其他方法来管理CSS。这是一种方法。