reactjs + styled-components与有状态组件 - 我的风格无法看到道具

时间:2018-04-05 22:33:17

标签: javascript reactjs styled-components

为什么在使用类/有状态组件时看不到道具:

const StyledTitle = styled.h1 `
  color: ${props => (props.primary ? "royalblue" : "black")};
`;

class Title extends Component {
  render() {
    return <StyledTitle > {
      this.props.children
    } < /StyledTitle>;
  }
}

const App = () => ( 
  <div>
    <Title>Hi, Alice!</Title>
    <Title primary>Hi Bob, you are awesome!</Title>
  </div>
);

这是Styled-Components&#39;例: Adapting based on props

演示:https://codesandbox.io/s/oxqz3o30w5

1 个答案:

答案 0 :(得分:3)

您没有将primary属性传递给样式化组件,因此它可以根据primary属性呈现逻辑。只需将其添加到组件声明中即可。

const StyledTitle = styled.h1 `
    color: ${props => (props.primary ? "royalblue" : "black")};
`;

class Title extends Component {
  render() {
    return <StyledTitle primary={this.props.primary}> {
      this.props.children
    } < /StyledTitle>;
  }
}

const App = () => ( 
  <div>
    <Title>Hi, Alice!</Title>
    <Title primary>Hi Bob, you are awesome!</Title>
  </div>
);