单击d3树节点文本this.props.history.push时,d3 + react.js出现错误“无法读取未定义的属性(阅读”props“)”

wztqucjr  于 2022-11-24  发布在  React
关注(0)|答案(2)|浏览(146)

在d3和react.js的帮助下,我能够创建d3层次树

我想实现的是,在每个节点文本(如约翰,卢克,...)点击它应该路由到每个点击文本的详细页面。

nodes
    .append("text")
    .attr("font-size", "17px")
    .attr("text-anchor", "start")
    .text(function (d) {
        return `${d.data.name}`
    })
    .on("click", function (event, d) {
        this.props.history.push(`/detail/${d.id}`);
});

构造器

constructor(props) {
    super(props);
    console.log(this.props)                  // there is history in props
    this.state = {
      isClicked: ""
      };
    this.geGraph = this.getGraph.bind(this);  // function where graph code presents

单击节点文本后,出现错误。

Uncaught TypeError: Cannot read properties of undefined (reading 'history')

同样,当我调试this.props.history.push行时,this中没有props
试图遵循这个How to use React Router with d3.js Graphs to redirect to another screen。仍然得到同样的问题。当我试图去箭头功能

.on("click", (event, d) => this.props.history.push(`/detail/${d.id}`))

这次道具出问题Uncaught TypeError: Cannot read properties of undefined (reading 'props')
我在<Route history={createBrowserHistory()}/>import { createBrowserHistory } from "history";中添加了历史,并从import { withRouter } from 'react-router-dom';导入了export default withRouter(MyGraph)

我使用的是路由器版本"react-router-dom": "^4.3.1"和基于类的组件(带有typescript)。

如何解决此问题。
提前感谢!

k5ifujac

k5ifujac1#

您正在不同的作用域上使用此函数,它的作用域现在是函数,最好在组件内为单击定义一个函数,并在单击事件上调用它。
或者,您可以将值存储在节点创建范围内的另一个变量中,并从该范围使用它。

dffbzjpn

dffbzjpn2#

根据javascript DOM API文档,对this的引用将是您将单击的DOM元素。

nodes
    .append("text")
    .attr("font-size", "17px")
    .attr("text-anchor", "start")
    .text(function (d) {
        return `${d.data.name}`
    })
    .on("click", function (event, d) {
        // try console.log here
        console.log(this);   // <--- most likely be a DOM element you clicked
        this.props.history.push(`/detail/${d.id}`); // <--- therefore this.props does not exist
});

溶液1

使用Javascript arrow function

.on("click", (event, d) => {
        console.log(this);   // <--- this should refer to the parent object
        this.props.history.push(`/detail/${d.id}`);
});

溶液2

或在构造函数中使用this绑定click事件处理程序
第一次

相关问题