css-in-javascript在React组件中使用

时间:2017-08-23 10:12:15

标签: css reactjs

根据这个引用https://github.com/airbnb/javascript/tree/master/css-in-javascript,样式化的JS组件应该这样写:

function MyComponent({ styles }) {
  return (
    <div {...css(styles.container)}>
      Never doubt that a small group of thoughtful, committed citizens can
      change the world. Indeed, it’s the only thing that ever has.
    </div>
  );
}

export default withStyles(() => ({
  container: {
    display: 'inline-block',
  },
}))(MyComponent);

我正在尝试编写一个简单的React组件,如下所示,但没有成功(我收到withStyles is not defined错误):

import React from 'react';

const MyComponent = ({styles}) => {
  return (
    <div {...css(styles.container)}>Hello World</div>
  )
}

export default withStyles(() => ({
  container: {
    color: 'red'
  },
}))(MyComponent);

我做错了什么?是否可以将此约定用于React组件?

1 个答案:

答案 0 :(得分:0)

你可以这样做

const divStyle = {
  color: 'blue',
  fontSize:10px
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!</div>;
}

但是你可以尝试其他更好的方法。请参考下面的链接:

https://medium.com/@aghh1504/4-four-ways-to-style-react-components-ac6f323da822