【发布时间】:2020-10-22 12:27:38
【问题描述】:
我想知道是否有办法将另一个反应组件附加到useRef 元素?
场景:当Parent的useEffect检测到Child的标题大于X大小时:添加另一个react组件。
- 我希望在
Parent上实现,因为在我的整个应用程序中,只有一个特定的情况需要我这样做。所以我不想修改核心的Child组件props。
import React, { ReactNode, useEffect, useRef } from 'react';
import { css } from 'emotion';
const someStyle = css`
background-color: red;
`;
type ChildProp = {
children: ReactNode;
};
const Child = React.forwardRef<HTMLHeadingElement, ChildProp>(
({ children }, ref) => {
return <h1>{children}</h1>;
},
);
const Parent = React.FunctionComponent = ()=> {
const childRef = useRef<HTMLHeadingElement>(null);
useEffect(() => {
if (childRef.current && childRef.current.clientHeight > 30) {
// append component to childRef.current
// e.g. childRef.current.append(<div className={someStyle}>hello</div>);
}
}, []);
return <Child ref={childRef}>hello world</Child>;
};
export default Parent;
【问题讨论】:
-
你不操作 DOM;使用 React,您可以使用条件渲染:
return <Child>hello world {childRef.current.clientHeight > 30 && <div>...</div>}</Child>;
标签: javascript reactjs append ref use-effect