【问题标题】:reactjs + styled-components with stateful component - my styles can't see propsreactjs + styled-components 有状态组件 - 我的样式看不到道具
【发布时间】:2018-04-06 06:43:52
【问题描述】:

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

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 的示例: Adapting based on props

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

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

    您没有将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>
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-11
      • 2018-06-19
      • 1970-01-01
      • 2021-11-04
      • 2020-08-31
      • 2018-11-12
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多