JavaScript/react/useImperativeHandle:修订间差异
来自康健生活
< JavaScript | react
创建页面,内容为“== 标题文本 == 父组件 {{hc|head=parent.tsx|output=<syntaxhighlight lang="bash"> import React, { useRef, useEffect } from 'react'; import ChildCET from './child'; export default function Parent() { const childRef = useRef<{ target: HTMLSpanElement | null; option: HTMLSpanElement | null }>({ target: null, option: null, }); useEffect(() => { const target = childRef.current.target; // todo }) return (<PageInfoCET ref={chi…” |
|||
| 第61行: | 第61行: | ||
export default ChildCET; | export default ChildCET; | ||
</syntaxhighlight>}} | </syntaxhighlight>}} | ||
或者 | |||
<syntaxhighlight lang="javascript"> | |||
useImperativeHandle<Editor | null, Editor | null>(instance, () => instanceRef.current as Editor); | |||
</syntaxhighlight> | |||
2024年9月14日 (六) 16:14的最新版本
标题文本
父组件
parent.tsx
import React, { useRef, useEffect } from 'react';
import ChildCET from './child';
export default function Parent() {
const childRef = useRef<{ target: HTMLSpanElement | null; option: HTMLSpanElement | null }>({
target: null,
option: null,
});
useEffect(() => {
const target = childRef.current.target;
// todo
})
return (<PageInfoCET
ref={childRef}></PageInfoCET>);
}
子组件
child.tsx
import React, { forwardRef, useRef, useEffect, MutableRefObject, useImperativeHandle } from 'react';
interface refs {
target?: HTMLDivElement | null;
option?: HTMLDivElement | null;
}
const FontFamilyCET = forwardRef<refs | null, {}>(({}, instance) => {
const target = useRef<HTMLSpanElement | null>(null);
const option = useRef<HTMLSpanElement | null>(null);
useImperativeHandle(instance, () => ({
get target() {
return target.current;
},
get option() {
return option.current;
},
}));
useEffect(() => {
const ref = instance as MutableRefObject<refs>;
// todo
})
return (<React.Fragment>
<span ref={target}></span>
<span ref={option}></span>
</React.Fragment>);
});
ChildCET.displayName = 'ChildCET';
export default ChildCET;
或者
useImperativeHandle<Editor | null, Editor | null>(instance, () => instanceRef.current as Editor);
No categories