我在我的React JS应用程序中有以下组件:
const Input = ({name, ..rest}) => {
return (
<div>
<input type="text" name={name} {...rest}/>
{errors && <span>错误:请添加您的姓名</span>}
</div>
);
};
rest参数包含所有React.InputHTMLAttributes<HTMLInputElement>,如required、className、id等。
我在尝试将style属性添加到Input组件时遇到了问题。如果我添加如下内容:
margin-bottom:45px
那么在输入框和span之间会出现空白,但是这个空白应该是整个组件的间距,所以间距应该应用在组件的下方而不是组件的元素之间。
如何避免这个问题并保留input标签上的...rest属性?
注意:除了style之外,还可以在相同的上下文中使用className、id、required等。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以从
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> ); };