简体   繁体   English

如何将 Ref 与 HTMLInputElement 一起使用?

[英]How can I useRef with HTMLInputElement?

Working with React and hooks:使用 React 和钩子:

I have this ParentCompontent which contains its own logic and content which rerenders when its props.otherStuff changes (as usual).我有这个ParentCompontent ,它包含自己的逻辑和内容,当它的props.otherStuff改变时(像往常一样) props.otherStuff渲染。 But I also have a special made InputComponent .但我也有一个特制的InputComponent The InputComponent renders a JSX.Element with an <input> with some basic attributes.所述InputComponent呈现一个JSX.Element与<input>一些基本属性。 One attribute is ref which is a function that returns the HTMLInputElement to the prop onSetInputRef .一个属性是ref ,它是一个将 HTMLInputElement 返回到道具onSetInputRef The only thing you need to know is that whichever function I place in the prop onSetInputRef gives me the HTMLInputElement as an argument so I can access it in the parent component.您唯一需要知道的是,我在道具onSetInputRef放置的任何函数onSetInputRef为我提供了HTMLInputElement作为参数,以便我可以在父组件中访问它。

How can i use my useRef and "set" it as the HTMLInputElement.我如何使用我的 useRef 并将其“设置”为 HTMLInputElement。 Is there a way?有办法吗? Also if that is possible.还有如果可能的话。 When props.otherStuff changes I still want to focus on that input element.props.otherStuff改变时,我仍然想关注那个输入元素。 Anyone that can help me?任何人都可以帮助我? Im not that good with ref..我对裁判不太好。。

So here is what i've tried:所以这是我尝试过的:

const ParentComponent = (props) => {

   const inputRef = React.useRef<HTMLInputElement>(null)

    React.useEffect(() => {
        inputRef.focus()
    }, [props.otherStuff]);

   const setRef = (inputElement: <HTMLInputElement>) => {
    inputRef = inputElement;
   }

return (
    <>
        <>
         {render props.otherStuff}
        </>
        <InputComponent
         ...otherProps
         onSetInputRef={setRef}
       />
     </>
    )
 }

You need to use the current property of your ref:您需要使用 ref 的current属性:

React.useEffect(() => {
  inputRef.current.focus()
}, [props.otherStuff]);

const setRef = (inputElement: HTMLInputElement) => {
  inputRef.current = inputElement;
}

I hope this helps.我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM