refs之新舊差異
阿新 • • 發佈:2019-03-25
官方 idm parent put 被調用 inpu api spa tro
Refs是什麽?
官方:Refs 提供了一種方式,用於訪問在 render 方法中創建的 DOM 節點或 React 元素。
16.3版本-Refs
使用方式:
1.首先使用React.createRef()創建refs
2.使用ref屬性獲取React元素(一般賦予在虛擬DOM上);
設置Refs
class MyComponent extends React.Component{ constructor(props){ super(props); this.ele = React.createRef();this.showRef=this.showRef.bind(this); } showRef(){ console.log(‘訪問refs中的值‘,this.ele.current) } render(){ return ( <div> <input type="text" ref={this.ele} onChange={this.showRef}></input> </div> ) } }
// {current:input} input 是DOM元素
訪問Refs
官方:const node = this.myRef.current;
ref的值取決於節點的類型:
- 當
ref
屬性被用於一個普通的 HTML 元素時,React.createRef()
將接收底層 DOM 元素作為它的current
屬性以創建ref
。 - 當
ref
屬性被用於一個自定義類組件時,ref
current
。 - 你不能在函數式組件上使用
ref
屬性,因為它們沒有實例
普通的HTML元素:
class CustomTextInput extends React.Component { constructor(props) { super(props); // 創建 ref 存儲 textInput DOM 元素 this.textInput = React.createRef(); this.focusTextInput = this.focusTextInput.bind(this); } focusTextInput() { // 直接使用原生 API 使 text 輸入框獲得焦點 // 註意:通過 "current" 取得 DOM 節點 this.textInput.current.focus(); } render() { // 告訴 React 我們想把 <input> ref 關聯到構造器裏創建的 `textInput` 上 return ( <div> <input type="text" ref={this.textInput} /> <input type="button" value="Focus the text input" onClick={this.focusTextInput} /> </div> ); } }
為類組件增加ref class AutoFocusTextInput extends React.Component { constructor(props) { super(props); this.textInput = React.createRef(); } componentDidMount() { this.textInput.current.focusTextInput(); } render() { return ( <CustomTextInput ref={this.textInput} /> ); } }
函數式組件-Refs(組件沒有實例-不能使用)
function MyFunctionalComponent() { return <input />; } class Parent extends React.Component { constructor(props) { super(props); this.textInput = React.createRef(); } render() { // 這將 *不會* 工作! return ( <MyFunctionalComponent ref={this.textInput} /> ); } }
函數式組件-Refs(組件內部可以使用)
function CustomTextInput(props) { // 這裏必須聲明 textInput,這樣 ref 回調才可以引用它 let textInput = null; function handleClick() { textInput.focus(); } return ( <div> <input type="text" ref={(input) => { textInput = input; }} /> <input type="button" value="Focus the text input" onClick={handleClick} /> </div> ); }
回調 Refs(主流) 類似於↑
class CustomTextInput extends React.Component { constructor(props) { super(props); this.textInput = null; this.setTextInputRef = element => { this.textInput = element; }; this.focusTextInput = () => { // 直接使用原生 API 使 text 輸入框獲得焦點 if (this.textInput) this.textInput.focus(); }; } componentDidMount() { // 渲染後文本框自動獲得焦點 this.focusTextInput(); } render() { // 使用 `ref` 的回調將 text 輸入框的 DOM 節點存儲到 React // 實例上(比如 this.textInput) return ( <div> <input type="text" ref={this.setTextInputRef} /> <input type="button" value="Focus the text input" onClick={this.focusTextInput} /> </div> ); } }
註意
如果 ref 回調以內聯函數的方式定義,在更新期間它會被調用兩次,第一次參數是 null ,之後參數是 DOM 元素。這是因為在每次渲染中都會創建一個新的函數實例。因此,React 需要清理舊的 ref 並且設置新的。通過將 ref 的回調函數定義成類的綁定函數的方式可以避免上述問題,但是大多數情況下無關緊要。
其實就是搬運的React官網........
refs之新舊差異