如何在Adobe React-Spectrum TextField组件中正确使用useRef?
解决方案
React Spectrum 的 TextField 组件没有将普通的 ref 属性透传到内部的原生 input 元素,官方提供了专属的 inputRef prop 用来绑定内部输入框的 DOM 引用,你只需要把原有代码中给 TextField 绑定的 ref 属性替换为 inputRef 即可:
const LoginForm = () => { // ref 类型可直接声明泛型,无需额外强制断言即可正常推导类型 const emailRef = useRef<HTMLInputElement>(null) const passwordRef = useRef<HTMLInputElement>(null) // ... 其余业务逻辑 return ( <Form isRequired necessityIndicator="label"> <TextField label="email" placeholder="secret@agent.com" isRequired value={email} onChange={setEmail} // 替换ref为inputRef即可绑定内部原生输入框 inputRef={emailRef} /> <TextField label="Password" placeholder="Password" isRequired type="password" value={password} onChange={setPassword} inputRef={passwordRef} /> <Button variant="cta" onPress={LogIn} marginTop="5%"> Log In </Button> </Form> ) }
绑定完成后你就可以通过 emailRef.current、passwordRef.current 直接访问到对应的原生 input DOM 元素,供 AuthenticationContext 调用。
内容的提问来源于stack exchange,提问作者NoobNewb
相关产品推荐
相关产品推荐

