V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
searene
V2EX  ›  JavaScript

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

  •  
  •   searene · 2017-08-12 22:30:11 +08:00 · 3371 次点击
    这是一个创建于 2442 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用 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,背景颜色就是默认的白色,有人知道是什么原因么?

    5 条回复    2017-08-13 22:49:20 +08:00
    crs0910
        1
    crs0910  
       2017-08-12 22:53:03 +08:00
    className
    searene
        2
    searene  
    OP
       2017-08-13 00:06:33 +08:00
    @crs0910 我猜你的意思大概是将 DivComponent 的返回值改成这样:

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

    但是如果 DivComponent 是一个第三方库,我不想修改它的代码,只通过修改 StyledDivComponent 能不能也达到同样的效果?
    sodatea
        3
    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
        4
    blanu  
       2017-08-13 05:52:08 +08:00 via iPhone
    想用 css 写法可以看 styled jsx
    zbinlin
        5
    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;
        }
    `;
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   904 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 20:53 · PVG 04:53 · LAX 13:53 · JFK 16:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.