简体   繁体   English

是否可以将`ref`用于TextNode?

[英]Is it possible to use `ref` for a TextNode?

This: 这个:

import React from "react";
import { render } from "react-dom";

let $container;

render(
  <b ref={e => ($container = e)}>
    {"one"}two{"six"}
  </b>,
  document.getElementById("root")
);

console.log($container);

will get me the <b> element: 将使我得到<b>元素:

<b>
  <!-- react-text: 2 -->
  "one"
  <!-- /react-text -->
  <!-- react-text: 3 -->
  "two"
  <!-- /react-text -->
  <!-- react-text: 4 -->
  "six"
  <!-- /react-text -->
</b>

But, what if I want a reference to one of the TextNodes? 但是,如果我要引用其中一个TextNode怎么办?
Is there a public api for this? 是否有公开的API? Maybe a special type for TextNodes so I can pass props to createElement ? 也许是TextNodes的一种特殊type ,所以我可以将道具传递给createElement吗?

No, you can't have a ref to those string literals with JSX. 不,您无法使用JSX引用这些字符串文字。 What this code is transformed to is: 这段代码转换为:

render(React.createElement(
  "b",
  { ref: function ref(e) {
      return $container = e;
    } },
  "one",
  "two",
  "six"
), document.getElementById("root"));

They are not React elements but strings, you can check it with the Babel Repl . 它们不是React元素,而是字符串,您可以使用Babel Repl进行检查。 One way to solve this problem is to wrap those elements in <span> tags, so then you can have a ref attached. 解决此问题的一种方法是将这些元素包装在<span>标记中,这样便可以附加引用。

$refs = {};

render(
  <b>
    <span ref={e => $refs.one = e}>one</span>
    <span ref={e => $refs.two = e}>{'two'}</span>
    <span ref={e => $refs.three = e}>three</span>
  </b>,
  document.getElementById("root")
);

Here's what I did: I created a component that solely consists of a text and referenced its TextNode in the DOM with ReactDOM.findDOMNode like so: 这是我做的事情:我创建了一个仅包含文本的组件,并使用ReactDOM.findDOMNode像这样在DOM中引用了它的TextNode

class TextNode extends React.Component {

  componentDidMount() {
      this.textNode = ReactDOM.findDOMNode(this); // Will be the DOM text node
  }

  render() {
    return this.props.text;
  }

}

In your example I could do something like this: 在您的示例中,我可以执行以下操作:

render(
  <b>
    <TextNode text={"one"} />
    <TextNode text="two" />
    <TextNode text={"six"} />
  </b>,
  document.getElementById("root")
);

The resulting HTML would not have any span s: 生成的HTML将没有任何span

<b>onetwosix</b>

while the DOM would have a <b> element with 3 text nodes inside. 而DOM将具有一个<b>元素,其中包含3个文本节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM