Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

javascript - Why can't I access children of a element rendered through React DOM?

I am trying to access the children of the measureDiv I created and appended with ReactDOM.create in the folllowing snippet, I am calling this function in a hook only on mount of the element. The problem is that the element's children are empty although it is rendered on the screen and visible in the inspector. I am able to access the children on the second render.

const containerRef = useRef<ReactNode | null>(null)

const measureElement = (element:any, layerId = "root") => {
  const measureLayer = document.createElement("div");
  measureLayer.setAttribute("class", "measure-div");
  measureLayer.setAttribute("id", "measure-div");

  ReactDOM.render(element, measureLayer);

  containerRef.current?.appendChild(measureLayer);

  const measureDiv = document.getElementById("measure-div");

  console.log(measureDiv, measureDiv.children.item(0))
}

useEffect(() => {
  measureElement(
    <BrowserRouter>
      <MuiThemeProvider theme={ManagementTheme}>
        <Element {...{props}/>
      </MuiThemeProvider>
    </BrowserRouter>
  )
}, [])

return (
  <Grid
      container
      className={classes.columnContainer}
      data-automation-id="test-answers-row"
      id="test-answers-row"
      ref={containerRef}
  />
)

My question is why can't I access the children that I render in a Node through ReactDOM.render right after I render them? And why I get them on the next render?

Incase you are wondering I am trying to render the element in a hidden div before rendering to the App to get its size to predict the layout.

question from:https://stackoverflow.com/questions/65648752/why-cant-i-access-children-of-a-element-rendered-through-react-dom

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From React docs:

ReactDOM.render() currently returns a reference to the root ReactComponent instance. However, using this return value is legacy and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root ReactComponent instance, the preferred solution is to attach a callback ref to the root element.

You can check it by delaying reading childs of root (measureLayer) element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...