简体   繁体   中英

React - how to append react component to useRef component during useEffect

I would like to know if there is a way to append another react component to the useRef element?

Scenario: when the Parent 's useEffect detects the Child 's heading to be bigger than X size: add another react component.

  • I would like the implementation to be on the Parent , because in my whole app, there was only one specific case where I need to do this. Therefore I did not want to modify the core Child component 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;

You should not manually manipulate the dom. React makes the assumption that it's the only one changing the page, so if that assumption is false it may make changes which overwrite yours, or skip changes that it doesn't realize it needs to do.

Instead, you should set state, causing the component to rerender. Then render something that matches what you want the dom to look like.

const Parent = React.FunctionComponent = ()=> {
  const childRef = useRef<HTMLHeadingElement>(null);
  const [large, setLarge] = useState(false);

  useEffect(() => {
    if (childRef.current && childRef.current.clientHeight > 30) {
      setLarge(true);
    }
  }, []);

  return (
    <React.Fragment>
      <Child ref={childRef}>hello world</Child>
      {large && (<div className={someStyle}>hello</div>)}
    </React.Fragment>
  )
};

PS: If you see the screen flicker with this code, consider changing it to useLayoutEffect instead of useEffect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM