当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - ReactDOM.findDOMNode with getAttribute("") returns null

问题描述:

I am defining tooltip as

<MACDTooltip ref="MACDTooltip" forChart={chartId} forDataSeries={dataSeriesId} key={`${chartId}-${dataSeriesId}`} calculator={macdCalculator}

onClick={logger.bind(null, { chartId, dataSeriesId }, options)} origin={[-48, 15]}/>

but in componentDidMount() method

ReactDOM.findDOMNode(this.refs.MACDTooltip).getAttribute("transform")

return null

ReactDOM.findDOMNode(this.refs.MACDTooltip)

returns

 <g><g class="react-stockcharts-toottip" transform="translate(-48, 15)"...</g></g>

and

ReactDOM.findDOMNode(this.refs.MACDTooltip).innerHTML

return "<g class="react-stockcharts-toottip" transform="translate(-48, 15)"></g>

How do i use ReactDOM.findDOMNode to get proper value

网友答案:

Since the g tags are nested, you want to find the childNode of it and get the attribute from there. Example:

class Example extends React.Component {
  componentDidMount() {
    console.log(
      ReactDOM.findDOMNode(this.refs.MACDTooltip).childNodes[0].getAttribute('transform')
    );
  }
  render() {
    return(
      <MACDTooltip ref="MACDTooltip" />
    );
  }
}

// Sample MACDTooltip class for demo.
class MACDTooltip extends React.Component {
  render() {
    return(
      <g>
        <g transform="Attribute"><text>Tooltip</text></g>
      </g>
    );
  }
}

ReactDOM.render(<Example />, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>
分享给朋友:
您可能感兴趣的文章:
随机阅读: