搜索

首页  >  问答  >  正文

使用CSS样式为ReactJs中的输入标签进行美化

<p>我在我的React JS应用程序中有以下组件:</p> <pre class="brush:php;toolbar:false;">const Input = ({name, ..rest}) => { return ( <div> <input type="text" name={name} {...rest}/> {errors && <span>错误:请添加您的姓名</span>} </div> ); };</pre> <p><code>rest</code>参数包含所有<code>React.InputHTMLAttributes<HTMLInputElement></code>,如required、className、id等。</p><p>我在尝试将<code>style</code>属性添加到Input组件时遇到了问题。如果我添加如下内容:</p> <p><code>margin-bottom:45px</code></p> <p>那么在输入框和span之间会出现空白,但是这个空白应该是整个组件的间距,所以间距应该应用在组件的下方而不是组件的元素之间。</p> <p>如何避免这个问题并保留input标签上的<code>...rest</code>属性?</p> <p>注意:除了<code>style</code>之外,还可以在相同的上下文中使用<code>className</code>、<code>id</code>、<code>required</code>等。</p>
P粉619896145P粉619896145539 天前658

全部回复(1)我来回复

  • P粉511896716

    P粉5118967162023-09-02 12:25:33

    您可以从rest中提取出style属性,然后删除其margin属性(之前设置的),并用您自定义的marginBottom: 45覆盖它。

    const Input = ({ name, style, ...rest }) => {
      const { margin, ...restStyles } = style;
      const newStyles = {
        ...restStyles,
        marginBottom: 45,
      };
    
      return (
          <div>
            <input type="text" name={name} {...rest} style={newStyles} />
                                                   // ^^^^^^^^^ 应用新样式
            {errors && <span>错误:请添加您的姓名</span>}
          </div>
      );
    };

    回复
    0
  • 取消回复