import { Input, Button } from 'antd';
import { useRef, createRef } from 'react';
import type { InputRef } from 'antd';
const RefDemo = () => {
const inputEL = useRef(null);
const inputEL2 = useRef(null);
const inputEL3 = createRef();
const getInput = () => {
console.log('antd DOM', inputEL.current?.input?.value);
console.log('原生 DOM', inputEL2.current?.value);
console.log('createRef', inputEL3.current?.value);
};
return (
antd Input:{width: 167}} />
原生 Input:
createRef Input:
);
};
export default RefDemo;
2. 作用于子组件,需要用到两个方法 useImperativeHandle 和 forwardRef
forwardRef:包裹要添加ref的子组件,有两个参数,组件的props和组件的refuseImperativeHandle:两个参数,组件的 ref 和一个回调函数,返回值是子组件的方法或者变量,提供给父组件调用注意!在父组件中使用 ref 去更新子组件,只是子组件更新,父组件不会同步更新,需要手动更新import { Button } from 'antd';
import { useRef, useImperativeHandle, forwardRef, useState } from 'react';
const Child = forwardRef((props, ref) => {
const [count, setCount] = useState(0);
useImperativeHandle(ref, () => ({
count: count,
changeCount() {
setCount(count + 1);
}
}));
return (
子组件count: { count }
);
});
type ChildRefType = {
count: number,
changeCount: () => void;
}
const RefDemo = () => {
const childRef = useRef();
const [reload, setReload] = useState(false);
const changeChild = () => {
childRef.current?.changeCount();
};
return (
父组件:count:{childRef.current?.count}
);
};
export default RefDemo;
注意!此方法不适用于createRef,原因如下,每次父组件渲染都会重新创建ref,所获取的值都为undefined
二、useRef和createRef区别
createRef会在组件每次渲染的时候重新创建useRef只会在组件首次渲染时创建import { useState, useRef, createRef } from 'react';
import { Button } from 'antd';
const RefDemo = () => {
const [count, setCount] = useState(0);
const inputEL = useRef(null);
const inputEL2 = createRef();
const showCount = () => {
console.log('useRef Input:', inputEL.current?.value);
console.log('createRef Input:', inputEL2.current?.value);
};
const updateComponent = () => {
setCount(count + 1);
};
console.log(inputEL.current?.value, inputEL2.current?.value, `组件${count === 0 ? '初' : count}次渲染`);
return(
useRef Input:
createRef Input:
);
};
export default RefDemo;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)