-1

動的に作成された DOM から特定の要素にアクセスしようとしています。その要素にカーソルを合わせると、それぞれの要素属性にアクセスしたいと思います。お気に入り、

// element creation inside render function
$.each(profiles, function(i,x){
  <span data-name={x.name} rel="tooltip">Name<span>
});

// tooltip initialization in componentDidMount function
var self = this;
$('body').tooltip({
        selector: '[rel=tooltip]',
        title: self.tooltipMsg
 });

関数は次のようになります。

tooltipMsg: function(element){
   return $(this).attr('data-name'); // this code is return undefined, since this refers to ReactClass
}

これを使用せずにtootipMsg関数内の特定の要素を取得するにはどうすればよいですか、または特定の要素を参照する必要がある「この」参照の代替手段はありますか?

静的要素の場合は、「ref」を使用できますhttps://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute しかし、私の場合、ref は動的です。

前もって感謝します。

4

2 に答える 2

0

私が質問 (およびコメント ダイアログ) を正しく理解している場合は、

  • 複数のツールチップ要素を作成する
  • toolTipMsg()表示されたツールチップの内容を読み取る何らかの機能を持っている

現在のセットアップは長い往復のように見えます:

  • 反応レンダリング関数内で、jQuery を使用して複数のツールチップ要素を作成し、それぞれに HTML data-name 属性を渡します
  • 反応コンポーネントDidMount内で、jQueryを使用してDOMからツールチップをフェッチし、リスナーをアタッチします
  • リスナーは、DOM から再度読み取り、ツールチップ HTML の data-name 属性をフェッチする関数を起動します。

jQuery と react を組み合わせて DOM を読み取る (またはさらに悪いことに、DOM を操作する) ことは、一般的には良い考えではありません。

更新:したがって、解決する2つの可能なルートがあります:

a. React のみのソリューション (NO jQuery、NO Bootstrap) React 内では、不要な場合は参照を使用しないようにすることをお勧めします。そして、あなたはそれらを必要としないようです。

変数を にバインドしてtoolTipMsg()、それを使用できます。そして、ツールチップの親にMouseOver リスナーを設定します。

React スタイルのコードは多かれ少なかれ次のようになります。

// tooltip element creation inside render function 
// of individual tooltip parent element
return 
  <div className="alwaysVisibleToolTipParent" 
    onMouseOver={this.toolTipMsg}>
    <p>someOtherContent</p>
    <span className="my-awesome-tooltip">{this.props.tooltipname}</span>
  </div>
});

// no need for componentDidMount: listener covered in initial render

// the function is much simpler now
tooltipMsg: function(){
   console.log(this.tooltipname);
}

このためのスタイリングを使用して独自のツールチップを作成する必要があります (残念ながら jQuery の利点はありません)。

b. 別の方法: Bootstrap と jQuery のみを使用する (反応なし) Bootstrap ツールチップは、リッスンできる独自のイベントを発生させます。(ドキュメントはこちら)。

あなたのコードでは、どこかで:

$('#myToolTipParent').on('shown.bs.tooltip', function () {
  // 'this' is now the element (parent of the tooltip)
  tooltipMsg(this);
})

そして、あなたのtooltipMsg()関数は次のようになります:

function tooltipMsg(element) {
  // the text of the tooltip == the title attribute of the parent element of the tooltip
  console.log(element.getAttribute("title"));
}
于 2015-10-30T15:22:57.797 に答える