简体   繁体   中英

Using props.type with react styled-components

hope you are keeping well. I'm stuck as to how to use the following props in my component.

const Container = styled.div`
    background-color: ${props =>
      ({
        primary: 'blue',
        danger: 'red',
        warning: 'yellow'
      })[props.type]
    }
`

and then in my app, I'm trying to do the following

...
<Container primary />
...

But there is no background-color change. I'm doing something stupid. Thanks in advance.

Passing props to the Styled component works exactly like in React. What you are doing is passing a prop named primary which has a type boolean .

In your Container, you are checking for type prop which is not there, so all you need to do pass a type prop with either one of this value primary | danger | warning primary | danger | warning

Code :

<Container type="primary" />

 const Container = styled.div` /* Background color with inline if/else. 'white' color is a fallbak */ background: ${props => props.primary ? "blue" : props.danger ? "red" : props.warning ? "yellow" : "white" }; /* You can do the same with other properties */ color: ${props => props.primary ? "white" : "#222"}; /* More properties will be applied to all */ font-size: 1em; height: 500px; padding: 0.25em 1em; `; const App = () => { return ( <div className="App"> <Container danger>Hello World!</Container> </div> ) } ReactDOM.render( <App /> , document.getElementById('root'))
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/4.3.2/styled-components.js"></script> <div id="root"></div>

See more examples at styled-components Docs

The closest solution to what you trying to achieve it using some other property than boolean :

// type = 'primary' / 'danger' / 'warning'
<Container type={type} />;

const TYPE = {
  primary: 'blue',
  danger: 'red',
  warning: 'yellow'
};

const Container = styled.div`
  background-color: ${({ type }) => TYPE[type]};
`;

As for your current code, you can try:

// Only `blue` or `red`
const Container = styled.div`
  background-color: ${({ primary }) => (primary ? 'blue' : 'red')};
`;

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