[Docs] React.cloneElement and forwarding ref
還沒有人認領這個 Issue。
- 主要語言
- JavaScript
- 星號
- 11.8k
- 分支
- 7.9k
- 平均合併
- 1 天 11 小時
- 30 天內合併 PR
- 11
描述
Hi, I believe the documentation about React.cloneElement is not very clear about handling refs.
I am talking about that part: https://reactjs.org/docs/react-api.html#cloneelement
However, it also preserves refs. This means that if you get a child with a ref on it, you won’t accidentally steal it from your ancestor. You will get the same ref attached to your new element.
Now, let's see consider the following use case (simplified):
const ChangeTitle = ({ children, ...otherProps }) =>
React.cloneElement(children, {
...otherProps,
title: 'Title was changed'
})
function MyComponent() {
const myRef = React.useRef()
return (
<ChangeTitle ref={myRef}>
<span>This is my component</span>
</ChangeTitle>
)
}
This throws a console warning about ChangeTitle unable to hold a ref.
In my original understanding of the docs, I though ChangeTitle would become the cloned element, which, as the docs explains, retain it's original ref, hance the one given by Mycomponent.
Instead, this is obviously wrong, and the cloned element would only retain a ref if it was given to itself, not the parent component, hence something like <span ref={spanRef}>This is my component</span>.
I guess the fix to the above code is the following:
const ChangeTitle = React.forwardRef(({ children, ...otherProps }, ref) =>
React.cloneElement(children, {
...otherProps,
ref,
title: 'Title was changed'
}))
Correct?
Is it worth adding specifically that cloneElement can contain the ref prop if used with React.forwardRef in a functional component?
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
查看 issue 中連結的 React API cloneElement 部分,並將其中關於 ref 的措辭與提供的 ChangeTitle 範例進行比較。釐清保留的是哪個 ref,以及 React.forwardRef 如何傳遞 ref;當說明準確描述警告與修正後的用法時即完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- react
- 領域
- documentation
- Issue 類型
- 文件
- 難度
- 2/5
- 預估耗時
- 1-3 小時
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 48/100