Use CSS styles to beautify input tags in ReactJs
P粉619896145
P粉619896145 2023-09-01 17:00:09
0
1
612
<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粉619896145
P粉619896145

reply all(1)
P粉511896716

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>
  );
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!