简体   繁体   中英

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

You are not passing the primary property to the styled component so it can render the logic depending on the primary property. 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>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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