简体   繁体   中英

styled component how to pass width props to component

I'm new in styled components . I want to set input width by passing props to component. Expected output should be :

<Input width=30px> or <Input width=100%> 

Here is my component:

import styled from "styled-components"

const UIInput = styled.input`
  padding: 5px;
  width: ${props => props.width ? width : 'auto'}
`

export default UIInput

In this little snippet: ${props => props.width ? width : 'auto'} ${props => props.width ? width : 'auto'} , you forget that width is on the props -object. To fix it:

${props => props.width ? props.width : 'auto'}

You can see my working example below:

 const UIInput = styled.input` padding: 5px; width: ${props => props.width ? props.width : 'auto'} ` ReactDOM.render( <div> <div> <p>300px</p> <UIInput width="300px" /> </div> <div> <p>80%</p> <UIInput width="80%"/> </div> </div>, document.getElementById('root')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script> <div id="root"></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