首頁  >  問答  >  主體

使用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>、<code>id</code>、<code>、<code> ;required</code>等。 </p>
P粉619896145P粉619896145414 天前603

全部回覆(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
  • 取消回覆