【问题标题】:Style attributes doesn't work on Input with suffix or prefix样式属性不适用于带后缀或前缀的输入
【发布时间】:2019-04-19 15:19:02
【问题描述】:

设置样式属性正在使用它。

 <Input
      style={{ borderWidth: this.state.focused ? "4px" : "1px" }}
      placeholder="this works"
      onMouseEnter={() => this.setState({ focused: true })}
      onMouseLeave={() => this.setState({ focused: false })}
    />

但是,当我使用Input 组件的后缀或前缀属性时,它不起作用。

    <Input
          style={{ borderWidth: this.state.focused ? "4px" : "1px" }}
          placeholder="not this"
          /*only difference is this suffix line*/
          suffix={<Icon type="save" />}
          onMouseEnter={() => this.setState({ focused: true })}
          onMouseLeave={() => this.setState({ focused: false })}
        />

当我在浏览器上查看源代码时,它给了我原因。

1.案例:

<input placeholder="this works" type="text" class="ant-input" style="border-width: 1px;">

2.案例:

<span class="ant-input-affix-wrapper" style="border-width: 1px;"><input placeholder="not this" type="text" class="ant-input"><span class="ant-input-suffix"><i class="anticon anticon-save"></i></span></span>

2.case span块吸收样式的原因。

running demo

那么如何在具有后缀/前缀属性的输入上设置我的样式。

【问题讨论】:

    标签: javascript reactjs input antd


    【解决方案1】:

    输入组件的实现不支持input 上的suffixprefix 属性上的style 属性。

    https://github.com/ant-design/ant-design/blob/3.10.7/components/input/Input.tsx#L170

    {prefix}
    {React.cloneElement(children, { style: null, className: this.getInputClassName() })}
    {suffix}
    

    您可以通过为Input 组件传递className 属性来解决此问题。

    假设您在样式表中有这些 CSS 定义,

    .border-sm input, input.border-sm {
      border-width: 1px;
    }
    
    .border-lg input, input.border-lg {
      border-width: 4px;
    }
    

    Inputs 的实现可能如下所示:

    //...
    import "./style.css"
    
    class ErrorExample extends React.Component {
      //...
    
      render() {
        return (
          <div>
            <h1>Enter mouse into one of textboxes</h1>
            <Input
              className={this.state.focused ? "border-lg" : "border-sm"}
              //...
            />
            <Input
              className={this.state.focused ? "border-lg" : "border-sm"}
              suffix={<Icon type="save" />}
              //...
            />
          </div>
        );
      }
    }
    

    【讨论】:

    • 感谢您的回答。问题是样式是动态创建的,所以我不能在 CSS 文件上写属性。因此,它不能解决我的问题:/
    猜你喜欢
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 2014-12-09
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多