【问题标题】:styled component how to pass width props to component样式化组件如何将宽度道具传递给组件
【发布时间】:2019-09-23 21:54:24
【问题描述】:

我是样式组件的新手。我想通过将道具传递给组件来设置输入宽度。 预期输出应该是:

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

这是我的组件:

import styled from "styled-components"

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

export default UIInput

【问题讨论】:

    标签: javascript reactjs styled-components css-in-js


    【解决方案1】:

    在这个小sn-p:${props =&gt; props.width ? width : 'auto'} 中,您忘记了widthprops 对象上。修复它:

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

    您可以在下面看到我的工作示例:

    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>

    【讨论】:

    • 怎么样:${props => props.width || '自动'}
    • @FabioEspinosa 当然是一个选项,我只是修复了 OP 的代码。我实际上认为新的空合并运算符会更好:${props =&gt; props.width ?? 'auto'}。现在如果props.width 是假的(例如0)它会默认为auto,也许你想要那个0?
    猜你喜欢
    • 2020-10-28
    • 2020-04-10
    • 1970-01-01
    • 2018-10-09
    • 2017-08-17
    • 2019-03-31
    • 2021-06-29
    • 2018-10-10
    • 2018-02-03
    相关资源
    最近更新 更多