React自定义Input组件如何传递label文本参数及正确调用
错误原因
你的组件写法不符合React函数组件的传参规则:
- React函数组件仅接收唯一的props对象作为入参,所有在JSX上给组件传递的属性,都会被挂载到这个对象上,直接声明第二个形参
label永远拿不到你传入的值 - 你将input的
id硬编码为input,如果页面多次渲染该组件,会出现id重复,导致label和input的关联失效。
修正方案
1. 调整组件定义
把label合并到props的类型声明中,同时从props里解构出自定义属性,避免无效属性透传给原生input:
import './InputAnimation.scss' import { InputHTMLAttributes } from 'react'; // 扩展原生input属性类型,新增label必填字段 type InputProps = InputHTMLAttributes<HTMLInputElement> & { label: string; }; export function InputAnimation(props: InputProps){ // 解构出自定义属性,剩余属性透传给原生input const { label, id, ...inputProps } = props; // 优先使用外部传入的id,未传入时基于label生成唯一id,避免多实例id冲突 const realInputId = id ?? `form-input-${label.replace(/\s+/g, '-')}`; return( <div className="form"> <input id={realInputId} className="form__input form-control" {...inputProps}/> <label htmlFor={realInputId} className="form__label">{label}</label> </div> ) }
2. 组件调用方式
调用时直接把label作为组件属性传入即可:
<InputAnimation type="password" placeholder=" " label="登录密码" onChange={event => setPassword(event.target.value)} value={password} />
注意事项
- 所有自定义组件参数都要作为props的属性传递,不要给函数组件添加额外的形参
- 自定义属性如果不需要透传给原生DOM元素,一定要在展开props前解构出来,否则会触发React的无效DOM属性警告
- 表单关联的id不要硬编码,否则同页面多组件实例会出现交互异常
内容的提问来源于stack exchange,提问作者Gabriel Donada
相关产品推荐
相关产品推荐

