跳到主要内容
版本:Next

useRef

1.useRef 与 useImperativeHandle

子组件 :
import React, { forwardRef } from "react";
// 子组件
function Child(props, ref) {
const inputRef = React.useRef();
const divRef = React.useRef();
React.useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
divChange: () => {
divRef.current.style.backgroundColor = "green";
},
a() {
console.log("a方法");
},
}));
return (
<div style={{ backgroundColor: "yellow", padding: 5 }} ref={divRef}>
子组件 : <input ref={inputRef} />
</div>
);
}
const FancyInput = forwardRef(Child);

// 父组件
function App() {
let inputRef = React.useRef();
function changeText() {
console.log(inputRef); //{focus: ƒ, a: ƒ}
inputRef.current.focus(); //input聚焦
inputRef.current.a();
}
return (
<div style={{ backgroundColor: "rgba(0,0,0,.2)", padding: 5 }}>
<div>
<button
onClick={() => {
changeText();
}}
>
获取input焦点
</button>
<button
onClick={() => {
inputRef.current.divChange();
}}
>
改变子组件的div背景色
</button>
</div>
<FancyInput ref={inputRef} />
</div>
);
}
export default App;

2.useRef 与 createRef

import React, { useState, useEffect, createRef, forwardRef } from "react";
const InputRef = ({ defaultValue, max }, ref) => {
const [value, setvalue] = useState(defaultValue || "");
return (
<div>
<input
ref={ref}
value={value}
onChange={(e) => {
setvalue(e.target.value);
}}
/>
<span
onClick={() => {
setvalue(max);
}}
>
最大
</span>
</div>
);
};
// 函数组件转发
const Input = forwardRef(InputRef);

export default function AsycList() {
const [refArr, setRefArr] = useState([]); // ref数组
const [data, setData] = useState([]); // 获取的数据

// 模拟请求
const getRefArr = async () => {
const { data } = await new Promise((resolve, reject) => {
resolve({
data: [
{
value: 23,
},
{
value: 22,
},
{
value: 2,
},
],
});
});
setData(data);
const arr = data.map(() => {
return createRef();
});
setRefArr([...arr]);
};

useEffect(() => {
getRefArr();
}, []);
return (
<div style={{ backgroundColor: "yellow" }}>
{refArr?.map((item, index) => (
<div key={JSON.stringify(data[index])}>
<Input
ref={item}
defaultValue={data[index].value}
max={data[index].value}
></Input>
<button onClick={() => console.log(item.current)}>测试</button>
</div>
))}
</div>
);
}