如何在hooks的元素使用useRef()數組多個multiple refs?

12 月 25, 2019 | | 0 條留言

react提出一種Refs概念,使用這個方法,我們就可以抓取到react裡面的DOM元素,那hooks該如何使用Refs呢? ## useRef 語法 const refContainer = useRef(initialValue); ` useRef返回一個可變的ref對象,其.current屬性被初始化為傳遞的參數(initialValue)。返回的對象將存留在整個組件的生命週期中。 從本質上講,useRef就像一個“盒子”,可以在其.current財產中保持一個可變的價值。 ref對像是一個通用容器,其當前屬性是可變的,可以保存任何值(可以是元素,對象,基本類型,甚至函數),而不是類上的實例屬性。 下面這個例子中展示了可以在useRef()生成的ref的current中存入元素,字符串 ` import React, { useRef, useState, useEffect } from \\\'react\\\'; export default () => { // 使用 useRef 創建 inputEl const inputEl = useRef(null); const [text, updateText] = useState(\\\'\\\'); // 使用 useRef 創建 textRef const textRef = useRef(); useEffect(() => { // 將 text 值存入 textRef.current 中 textRef.current = text; console.log(\\\'textRef.current:\\\', textRef.current); }); const onButtonClick = () => { // current points to the mounted text input element inputEl.current.value = Hello, useRef; }; return ( {/* 保存 input 的 ref 到 inputEl */} 在 input 上展示文字 updateText(e.target.value)} /> ); } ## 在多個元素中使用useRef() ref最初只是{ current: null }對象。useRef在組件渲染之間保留對此對象的引用。currentvalue主要用於組件引用,但可以容納任何內容。 import React, { useRef, useCallback } from \'react\'; const App = props => { const itemsRef = useRef([]); // you can access the elements with itemsRef.current[n] const handleChange = useCallback(() => { const yearmonth = inputRef.current[0].value; const optionselc = inputRef.current[1].value; console.log(yearmonth); //2019-11 console.log(optionselc); //0 or 1 }, []); return ( handleChange()} ref={el => (inputRef.current[0] = el)} className=input-medium defaultValue={${new Date().getFullYear()}-${+new Date().getMonth() + 1}} > handleChange()} ref={el => (inputRef.current[1] = el)} > web app ); } 參考內容: [How can I use multiple refs for an array of elements with hooks?](https://stackoverflow.com/questions/54633690/how-can-i-use-multiple-refs-for-an-array-of-elements-with-hooks) [React Hooks 使用详解](https://juejin.im/post/5caaa8ffe51d452b2b027f8a)