原生JavaScript React如何继承HTML button、input等元素的原生props
React 原生JS继承HTML元素props的实现方案
原生JavaScript版本的React实现该需求比TypeScript更简单,无需额外做类型声明,直接通过对象展开运算符透传剩余属性即可实现继承所有原生元素的props。
封装自定义Button示例
// 自定义Button组件 function CustomButton(props) { // 先提取组件自定义参数,剩余参数全部透传给原生button const { children, customStyle = 'default', ...nativeProps } = props; return ( <button className={`custom-btn custom-btn-${customStyle}`} // 所有原生button支持的props都会被传递生效,比如onClick、disabled、type等 {...nativeProps} > {children} </button> ) } // 组件使用示例 <CustomButton type="submit" disabled onClick={() => console.log('点击触发')} customStyle="primary"> 提交 </CustomButton>
封装自定义Input示例
// 自定义Input组件 function CustomInput(props) { const { label, ...nativeProps } = props; return ( <div className="input-group"> {label && <span className="input-label">{label}</span>} <input {...nativeProps} /> </div> ) } // 组件使用示例 <CustomInput label="密码" type="password" placeholder="请输入密码" onChange={(e) => console.log(e.target.value)} />
注意事项
- 若自定义组件和原生元素存在同名props,可根据需求调整赋值顺序:固定属性写在展开运算符后可覆盖传入的参数,写在前面则会被传入的参数覆盖
- 所有原生元素支持的事件、属性都可以直接在自定义组件上传递,无需额外声明
内容的提问来源于stack exchange,提问作者otto
相关产品推荐
相关产品推荐

