用ref代替findDOMNode

问题描述 投票:1回答:1

谁能帮我理解一下如何使用ref来代替findDOMNode?请看我的代码。

class Node extends Component {
  componentDidMount() {
    this.d3Node = d3.select(ReactDOM.findDOMNode(this))
      .datum(this.props.data)
      .call(FORCE.enterNode)
  }

  componentDidUpdate() {
    this.d3Node.datum(this.props.data)
      .call(FORCE.updateNode)
  }

  render() {
    return (
      <g className='node'>
        <circle onClick={this.props.addLink}/>
        <text>{this.props.data.name}</text>
      </g>
    );
  }
}

export default Node;

谢谢

javascript reactjs d3.js dom ref
1个回答
1
投票

如何使用refs文档。https:/reactjs.orgdocsrefs-and-the-dom.html

class Node extends React.Component {
  constructor(props) {
    super(props)
    this.gRef = React.createRef()
  }
  componentDidMount() {
    this.d3Node = d3.select(this.gRef.current)
      .datum(this.props.data)
      .call(FORCE.enterNode)
  }

  componentDidUpdate() {
    this.d3Node.datum(this.props.data)
      .call(FORCE.updateNode)
  }

  render() {
    return (
      <g className='node' ref={this.gRef}>
        <circle onClick={this.props.addLink}/>
        <text>{this.props.data.name}</text>
      </g>
    );
  }
}

export default Node;
© www.soinside.com 2019 - 2024. All rights reserved.