使用CSS样式为ReactJs中的输入标签进行美化
P粉619896145
P粉619896145 2023-09-01 17:00:09
0
1
653
<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粉619896145
P粉619896145

全部回复(1)
P粉511896716

您可以从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>
  );
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板