使用CSS样式为ReactJs中的输入标签进行美化
P粉619896145
2023-09-01 17:00:09
<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>
您可以从
rest
中提取出style
属性,然后删除其margin
属性(之前设置的),并用您自定义的marginBottom: 45
覆盖它。