我有需要内部样式的 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)
语句吗?
最佳答案
这是一种不同的方法,但请查看 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 中定义样式并导入它们。
关于javascript - 在服务器上渲染需要样式的 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29282530/