react提出一種Refs概念,使用這個方法,我們就可以抓取到react裡面的DOM元素,那hooks該如何使用Refs呢?
語法
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 (
<div>
{/* 保存 input 的 ref 到 inputEl */}
<input ref={ inputEl } type="text" />
<button onClick={ onButtonClick }>在 input 上展示文字</button>
<br />
<br />
<input value={text} onChange={e => updateText(e.target.value)} />
<div/>
);
}
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 (
<div>
<input
id="month"
type="month"
name="month"
onClick={() => handleChange()}
ref={el => (inputRef.current[0] = el)}
className="input-medium"
defaultValue={`${new Date().getFullYear()}-${+new Date().getMonth() +
1}`}
></input>
<select
name="seupdate"
className="input-small"
onClick={() => handleChange()}
ref={el => (inputRef.current[1] = el)}
>
<option value="0">web</option>
<option value="1">app</option>
</select>
</div>
);
}
參考內容:
How can I use multiple refs for an array of elements with hooks?
React Hooks 使用详解
© UCAMC. All rights reserved.
Powered by CITIAR.