【问题标题】:Get text content from node in React从 React 中的节点获取文本内容
【发布时间】:2018-05-19 19:49:18
【问题描述】:

从节点中提取文本有点麻烦。

节点是一个段落。

 <p className="Blend" refs="hello"> { `${this.state.landing}?utm_campaign=${this.state.utm}` } </p>

我正在尝试在函数中将节点的内容记录到控制台。

 makeSmall = () => {
        var text = this.refs.hello.innerText
        console.log(text)
      }

但是,此控制台没有返回任何内容。我也尝试过通过 className 访问节点。

在 React 中访问文本的正确方法是什么?

【问题讨论】:

  • 我相信你在refs 属性的&lt;p&gt; 元素中有一个类型,这应该是ref

标签: reactjs dom


【解决方案1】:

const getNodeText = node => {
  if (['string', 'number'].includes(typeof node)) return node
  if (node instanceof Array) return node.map(getNodeText).join('')
  if (typeof node === 'object' && node) return getNodeText(node.props.children)
}

const printHTML = ref => ref && (ref.innerText = document.querySelector('h1').outerHTML)

https://codesandbox.io/s/react-getnodetext-h21ss

  // in the picture
  {heading} // <Heading>Hello <span className="red">Code</span>Sandbox</Heading>
  <pre ref={printHTML}/>
  <pre>{getNodeText(heading)}</pre>

最初来自这里https://stackoverflow.com/a/60564620/985454

【讨论】:

    【解决方案2】:

    感谢大家的贡献。我以前的方法有一些错误。

    即,尝试在函数中设置 ref。以下是我为使其工作而采取的步骤。

    1) 使用 React.createRef() 构造 ref; (new in react 16)

    class Newone extends Component {
        state = {
            allocation: "Acq",
          };
          textUrl = React.createRef();
    

    2) 将 ref 附加到适当的节点

     <p className="Blend" ref={this.textUrl}> { `${this.state.landing}?utm_campaign=${this.state.utm}` } </p>
    

    3) 使用 value.innertext 引用 ref

    handleLinkClick = (event) => {
    bitly.shorten(this.textUrl.value.innerText) 
    

    **确保您使用的是 React 版本 16.3.0-alpha.1。

    以下是控制台的屏幕截图。

    bitly.shorten(this.textUrl)

    bitly.shorten(this.textUrl.value)

    bitly.shorten(this.textUrl.value.innerText)

    如果您只想返回节点中的文本,请确保附加 innerText。

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      您的&lt;p&gt; 属性中有错字,

      你写的:

      <p className="Blend" refs="hello"> { `${this.state.landing}?utm_campaign=${this.state.utm}` } </p>
      

      这应该是:

      <p className="Blend" ref="hello"> { `${this.state.landing}?utm_campaign=${this.state.utm}` } </p>
      

      refs 属性有问题,应该是ref

      供参考:(查看浏览器控制台或站内控制台)See this sandbox

      希望这会有所帮助!

      【讨论】:

        【解决方案4】:

        也许您需要将段落的文本保存到状态并显示它。所以你会知道这个值:

         state = { msg: `${landing}?utm_campaign=${utm}` } 
         ...
         <p className="Blend"> { ${this.state.msg} } </p>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-07
          相关资源
          最近更新 更多