代码之家  ›  专栏  ›  技术社区  ›  Nat

如何使具有一些动态CSS属性的可重用样式化组件

  •  0
  • Nat  · 技术社区  · 5 年前

    例如,我有一个InputField组件:

    import React from "react";
    import styled from "styled-components";
    
    const InputFieldContainer = styled.input`
      background: #252c37;
      border-radius: 15px;
      border: 0px;
      width: 80%;  ///   THESE TWO I HAVE 
      height: 75px; //   HARDCODED THE SIZE 
      font-size: 30px;
      color: white;
      padding-left: 15px;
      margin-bottom: 30px;
      &::placeholder {
        color: white;
      }
    `;
    
    function InputField(props) {
      return (
        <div>
          <InputFieldContainer
            type={props.type}
            value={props.value}
            name={props.name}
            placeholder={props.placeholder}
            onChange={props.onChange}
          />
        </div>
      );
    }
    
    export default InputField;
    

    但是,每次使用此组件时,我都希望能够在每次使用时更改一些值(如宽度和高度)。换言之,我不想硬编码一些CSS值,只想获得一旦使用它们就能够指定它们的能力。

    <InputField
          type="password"
          value={null}
          placeholder="password"
          label="password"
          name="password"
          onChange={null}
          width = "100px". // I know this isn't possible, but used as example
     ></InputField>
    

    我知道可能有一些方法可以通过使用CSS的优先级列表(内联CSS等)来解决这个问题,但是肯定有一个更健壮/更干净的方法吗?

    1 回复  |  直到 5 年前
        1
  •  2
  •   Guerric P    5 年前

    你可以像这样把它们当作道具传递。更多信息请参见 docs :

    const InputFieldContainer = styled.input`
      background: #252c37;
      border-radius: 15px;
      border: 0px;
      width: ${({ width }) => width};
      height: ${({ height}) => height};
      font-size: 30px;
      color: white;
      padding-left: 15px;
      margin-bottom: 30px;
      &::placeholder {
        color: white;
      }
    `;
    
    function InputField(props) {
      return (
        <div>
          <InputFieldContainer {...props}/>
        </div>
      );
    }
    
    export default InputField;