在 React 中,ref 是用來獲取組件或 DOM 元素的引用的一種方式。ref 可以在組件掛載后被訪問,并且允許您從組件中訪問底層的 DOM 元素或組件實例。
ref 有兩種用法:字符串 ref 和回調(diào)函數(shù) ref。文章來源:http://www.zghlxwxcb.cn/news/detail-807824.html
- 字符串 ref(string refs)是一種早期的使用 ref 的方式。它通過設(shè)置 ref 屬性為一個字符串,將 ref 關(guān)聯(lián)到一個 DOM 元素或組件實例上。然后可以通過 this.refs 獲取這個 ref。
class MyComponent extends React.Component { componentDidMount() { const input = this.refs.myInput; input.focus(); } render() { return( <div> <input type="text" ref="myInput" /> </div> ); } }
- 回調(diào)函數(shù) ref(callback refs)是一種現(xiàn)代而常用的使用 ref 的方式。它通過設(shè)置 ref 屬性為一個回調(diào)函數(shù),將 ref 關(guān)聯(lián)到一個 DOM 元素或組件實例上。當(dāng)組件掛載或卸載時,React 會調(diào)用這個回調(diào)函數(shù),并將 DOM 元素或組件實例作為參數(shù)傳遞進去。
class MyComponent extends React.Component { constructor(props) { super(props); this.inputRef = null; } componentDidMount() { this.inputRef.focus(); } setInputRef = (ref) => { this.inputRef = ref; }; render() { return ( <div> <input type="text" ref={this.setInputRef} /> </div> ); } }
需要注意的是,字符串 ref 在 React v16.3 之后被廢棄了,建議使用回調(diào)函數(shù) ref。此外,對于函數(shù)組件,可以使用 useRef Hook 來獲取組件或 DOM 元素的引用文章來源地址http://www.zghlxwxcb.cn/news/detail-807824.html
到了這里,關(guān)于react中refs的作用是什么?有幾種用法?的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!