input自動聚焦問題
在react中可以使用refs解決這個問題,首先看一下refs的使用場景:
(1)處理焦點、文本選擇或媒體控制。
(2)觸發強制動畫。
(3)集成第三方 DOM 庫。
使用refs解決input聚焦的問題有兩種應用場景:
1、組件內部:
在input內部定義ref,當給 HTML 元素添加 ref 屬性時,ref 回調接收了底層的 DOM 元素作為參數。例如,下面的代碼使用 ref 回調來存儲 DOM 節點的引用。
class CustomTextInput extends React.Component { constructor(props) { super(props); this.focus = this.focus.bind(this); } focus() { // 直接使用原生 API 使 text 輸入框獲得焦點 this.textInput.focus(); } render() { // 使用 `ref` 的回調將 text 輸入框的 DOM 節點存儲到 React // 實例上(比如 this.textInput) return ( <div> <input type="text" ref={(input) => { this.textInput = input; }} /> <input type="button" value="Focus the text input" onClick={this.focus} /> </div> ); } }
2、父子組件:
子組件內input定義為:
import React from 'react'; class Input extends React.Component { constructor(props){ super(props); }; render() { return <input type="text" ref={this.props.inputRef}/>; } } export default Input;
父組件調用方法:
<Input name="中文姓" id="surname" placeholder="與身份證一致" inputRef={el => this.surname = el}/> componentDidMount() { this.surname.focus(); }
