简体   繁体   English

reactjs +带状态组件的样式组件-我的样式看不到道具

[英]reactjs + styled-components with stateful component - my styles can't see props

Why can't props be seen when using a class/stateful component: 为什么在使用类/有状态组件时看不到道具:

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>
);

Here is Styled-Components' example: Adapting based on props 这是样式化组件的示例: 基于道具的适应

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

You are not passing the primary property to the styled component so it can render the logic depending on the primary property. 您没有将primary属性传递给样式化的组件,因此它可以根据primary属性来呈现逻辑。 Just add it in the component declaration. 只需将其添加到组件声明中即可。

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>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM