reactjs / reactjs/react.dev

Adding ref with React.cloneElement() fails on class component with functional component error

オープン
#3,911 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
JavaScript
スター
11.8k
フォーク
7.9k
平均マージ
1日 11時間
マージ済み PR(30日)
11

説明

In a class component with all class component children...

constructor(props) {
  super(props);

  this.myref = React.createRef();
}

render() {

  return (
    {React.cloneElement(this.props.children[0], {ref: myref})}
  );
}

...fails with Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

I get that React.cloneElement() is probably returning a functional wrapper that's confusing React, but given the power of this.props.children, what is the proper way to dynamically add refs? All of the actual children are class components if that matters.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

報告では React.cloneElement()、React.createRef()、クラスコンポーネント、関数コンポーネントについて言及されていますが、リポジトリのファイルもテストのエントリーポイントも示されていません。まず、示されているコンポーネント構造で警告を再現し、期待される動作が React の修正なのか、ドキュメントの明確化なのかを判断してください。合意された再現可能な結果が得られ、文書化またはテストされた解決策がある状態を完了とします。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript, react
領域
frontend
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。