styled-components 不起作用,不知道是为什么

2017-08-12 22:30:11 +08:00
 searene

用 create-react-app 创建了一个工程,然后把 App.js 改成了如下代码:

import React, { Component } from 'react';
import styled from 'styled-components';
import logo from './logo.svg';
import './App.css';

class DivComponent extends Component {
  render() {
    return (
      <div>Test</div>
    )
  }
}

const StyledDivComponent = styled(DivComponent)`
  background-color: green;
`

class App extends Component {
  render() {
    return (
      <StyledDivComponent />
    );
  }
}

export default App;

本以为背景颜色会变成绿色,然而并没有,整个页面只显示了一个 Test,背景颜色就是默认的白色,有人知道是什么原因么?

3380 次点击
所在节点    JavaScript
5 条回复
crs0910
2017-08-12 22:53:03 +08:00
className
searene
2017-08-13 00:06:33 +08:00
@crs0910 我猜你的意思大概是将 DivComponent 的返回值改成这样:

<div className={this.props.className}>Test</div>

但是如果 DivComponent 是一个第三方库,我不想修改它的代码,只通过修改 StyledDivComponent 能不能也达到同样的效果?
sodatea
2017-08-13 01:56:01 +08:00
NOTE
styled-components always generates a real stylesheet with classes.
The classnames are then passed to the React component (including third party components) via the className prop.
blanu
2017-08-13 05:52:08 +08:00
想用 css 写法可以看 styled jsx
zbinlin
2017-08-13 22:49:20 +08:00
@searene 如果知道这些组件的 class,可以使用这种方式 wrap 一下:

class DivComponent extends Component {
    render() {
        return (
            <div className="test">Test</div>
        );
    }
}

const StyledDivComponent = styled(props => <div className={props.className}><DivComponent {...props} /></div>)`
    background-color: green;
    & > .test {
        color: red;
    }
`;

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/382504

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX