import React from 'react'
import { useRef } from 'react'
export default function App() {
//声明一个元素,一开始不知道这个元素指向哪个标签,先置为null
const element = useRef(null)
const handleClick = () => {
//获取input的值的方式
console.log(element.current.value)
}
return (
<div>
{/* element指向了这个元素 */}
<input type="text" ref={ element }/>
<button onClick={ handleClick }>获取input的值</button>
</div>
)
}
有一个需求:RefDemo里一个input需要页面刷新时聚焦(传统做法是用inputDom.focus()):
import React from 'react';
function Input() {
return <input />
}
export default function RefDemo() {
return (
<div>
<Input />
</div>
);
}
现在用上useRef就可以这么写:
import React, { useEffect, useRef } from 'react';
function Input() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef}/>
}
export default function RefDemo() {
return (
<div>
<Input />
</div>
);
为了更统一,需要在组件的父级写,就可以改成这样,还可以传递value:
import React, { useEffect, useRef } from 'react';
const Input = React.forwardRef((props, ref) => {
return <input ref={ref}/>
})
export default function RefDemo() {
const aref = useRef();
useEffect(() => {
aref.current.focus();
// deliver value
aref.current.value = "hello, world";
}, []);
return (
<div>
<Input ref={aref}/>
</div>
);