【问题标题】:Unbale to read the current dataset elements using d function in an onclick event无法在 onclick 事件中使用 d 函数读取当前数据集元素
【发布时间】:2022-01-14 21:14:22
【问题描述】:

当我创建的圆圈上发生单击事件时,我正在尝试控制台记录作为对象项(在本例中为圆圈)的 ID 给出的随机数。我尝试通过定义一个 onClick 函数和在 FruitBowl.js 模块中调用它。使用以下代码时出现未定义的错误。

import { select,range  } from 'd3';
    import {fruitBowl} from './fruitBowl';
    const svg = select('svg');
    
    const makeFruit = type => ({
      type,
      id: Math.random()
    });
    let fruits = range(5)
        .map(() => makeFruit('apple'));
    let selectedFruit= null;
    const onClick= d => {
        selectedFruit= d.id;
      render();
    };
    
    const render = () => {
        fruitBowl(svg,{
                    fruits,
              height:+svg.attr('height'),
                    onClick
      });
    };
    
    render();
    
    setTimeout(() => {
        fruits.pop();
        render();
    },1000);
    
    setTimeout(() => {
        fruits[2].type = 'lemon';
        render();
    },2000);
    
    setTimeout(() => {
        fruits = fruits.filter((d,i)=> i !==1); //to select all elements except element 2
        render();
    },3000);

下面是被导出到 index.js 文件的fruitBowl.js 模块。

import { scaleOrdinal } from 'd3';
const colorScale = scaleOrdinal()
    .domain(['apple','lemon'])
    .range(['red','yellow']);
const radiusScale = scaleOrdinal()
    .domain(['apple','lemon'])
    .range([50,30]);

// function that does multiple operations like .enter and .exit

    export const fruitBowl =  (selection,props) =>{
      const {fruits,height,onClick} = props;
        const circles =selection.selectAll('circle')
         .data(fruits,d=>d.id);
      
      const xPosition = (d,i) => i*120+80;
    
      circles
        .enter().append('circle')
          .attr('cx',xPosition)
          .attr('cy',height/2)
          .attr('r',0)
        .merge(circles)     //merge operation of enter and updates
          .attr('fill',d => colorScale(d.type))
            .on("click",d => {
                console.log(d.id);
      })
        .transition().duration(1000)
            .attr('cx',xPosition)
          .attr('r',d =>radiusScale(d.type));
    
    
    
    //code to remove an element from the data
    circles.exit()
      .transition().duration(1000)
        .attr('r',0) 
      .remove();
      //.attr('fill','black');   
    };

【问题讨论】:

  • 请显示完整的错误信息,并指出代码中出现错误的行。
  • 嗨,欢迎来到 Stack Overflow!如果您可以创建代码的minimal reproducible example,最好是在runnable stack snippet 中,这将非常有帮助。这样,我们可以更轻松地回答您的问题,您也更有可能得到一个好的答案!

标签: javascript html css d3.js


【解决方案1】:

这肯定是你问题的一部分:

let selectedFruit= null;
const onClick = d => {
    /// selectedFruit= id; You need to reference the obj d
  selectedFruit= d.id; 
  render();
};

【讨论】:

  • 嗨..感谢您回答我的问题。但是即使添加了您建议的代码..直到给我“未定义”作为与以前相同的答案。
猜你喜欢
  • 2013-04-15
  • 2018-08-13
  • 1970-01-01
  • 2012-11-10
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
相关资源
最近更新 更多