Home  >  Q&A  >  body text

Use CSS styles to beautify input tags in ReactJs

<p>I have the following component in my React JS application: </p> <pre class="brush:php;toolbar:false;">const Input = ({name, ..rest}) => { return ( <div> <input type="text" name={name} {...rest}/> {errors && <span>Errors: Please add your name</span>} </div> ); };</pre> <p><code>rest</code>The parameters include all<code>React.InputHTMLAttributes<HTMLInputElement></code>, such as required, className, id, etc. </p><p>I'm having trouble trying to add the <code>style</code> attribute to an Input component. If I add something like this: </p> <p><code>margin-bottom: 45px</code></p> <p> Then there will be a blank space between the input box and span, but this blank should be the spacing of the entire component, so the spacing should be applied below the component rather than between the elements of the component. </p> <p>How can I avoid this problem and preserve the <code>...rest</code> attribute on the input tag? </p> <p>Note: In addition to <code>style</code>, you can also use <code>className</code>, <code>id</code>, <code> in the same context ;required</code>etc. </p>
P粉619896145P粉619896145414 days ago604

reply all(1)I'll reply

  • P粉511896716

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

    You can extract the style attribute from rest, then delete its margin attribute (set previously) and use your custom marginBottom: 45override it.

    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>
      );
    };

    reply
    0
  • Cancelreply