簡體   English   中英

如何將 ref 轉發到子組件?

[英]How do I forward a ref down to a child component?

react 文檔為父組件提供了一種使用forwardRef方法從子組件獲取 ref 的方法。 但是,我需要在子組件中獲取父組件的寬度。 有沒有辦法在子組件中轉發父級的 ref?

您可以只訪問父級中的 ref,進行適當的計算並將道具(在您的情況下為寬度)發送給子級。

<ChildComp parentWidth={ref.current && calc_for_ref} />

如果要從 child 獲取 parent 寬度,則需要使用 useEffect 觀察 parentRef 道具,因為 child 將在 parent 之前渲染

 const Child = (props) => { const {parentRef} = props const [parentWidth, setParentWidth] = React.useState(props.parentRef.current? props.parentRef.current.clientWidth: 0) React.useEffect(() => { if (..props.parentRef.current.clientWidth) { setParentWidth(props.parentRef,current.clientWidth) } }. [props.parentRef:current]) return <div>The parent width is {parentWidth}</div> } const Parent = () => { const ref = React,useRef(null) const style = { border: "solid 1px black", width. "234px", } return (<div ref={ref} style={style}> Parent component <Child parentRef={ref} /> </div>) } ReactDOM.render(<Parent />; document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM