簡體   English   中英

如何以編程方式將焦點設置在輸入上

[英]How to programmatically set focus on input

我嘗試以編程方式將焦點設置在輸入上,但由於某種原因,我的代碼無法正常工作。 希望有人能夠告訴我我做錯了什么。

class ParentComponent extends React.Component {
    inputRef = React.createRef<HTMLInputElement>()

    focusInput = ()=> {
       const node = this.inputRef.current

       if(node) {
         console.log(node) // <input type="number" value />
         node.focus() // However focus is not set on the input
       }
    }

    getInputRef = ()=> {
       return this.inputRef
    }

    render(){
       return <ChildComponent getInputRef={this.getInputRef} focusInput={this.focusInput} />
    }
}

const ChildComponent: React.FC<any> = ({getInputRef, focusInput})=> (
   <React.Fragment>
       <input 
         type="number"
         ref={()=>getInputRef()}
       />
       <button onClick={()=>focusInput()}>Set Focus</button>
   </React.Fragment>
)

您需要使用React.forwardRef將父組件中定義的ref傳遞給功能性子組件。 嘗試這樣的事情:

家長

class ParentComponent extends React.Component {
  inputRef = React.createRef();

  focusInput = () => {
    const node = this.inputRef.current;
    if (node) {
      node.focus();
    }
  };

  render() {
    return <ChildComponent ref={this.inputRef} focusInput={this.focusInput} />;
  }
}

孩子

const ChildComponent = React.forwardRef((props, ref) => {
  return (
    <div>
      <input ref={ref} />
      <button onClick={() => props.focusInput()}>Set Focus</button>
    </div>
  );
});

這是一個沙箱供您參考: https://codesandbox.io/s/reactforwardref-o1jtt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM