d3.exit()。remove()无法正常工作

时间:2019-05-11 13:33:29

标签: d3.js

我要删除我选择的行。 单击该行,我将找到该行,并使用所选内容删除相关数据。

因此,我强制将数据放入'deleteLine'函数中,但是总是删除第二行。即使当我将第二行的数据放入数据中时也是如此。

我想我不理解d3输入删除功能。请提供任何建议。

这是小提琴的例子 https://jsfiddle.net/victoriaVvv/c2pybvmd/90/

class Hello extends React.Component {
constructor(props){
super(props)
this.drawLine = this.drawLine.bind(this)
this.deletLine = this.deleteLine.bind(this);
this.data = [
{ source : 'a', target:'b', x1 : 0, y1 : 0, x2 : 100, y2 : 100 },
{ source : 'c', target:'d', x1 : 100, y1 : 0, x2 : 200, y2 : 200 }
];

}
    componentDidMount(){
    //this.setSVG();

    this.deleteLine();

    const svg = d3.select('#svg').append('svg')

      .attr("width", '100%').attr("height", 500)
      .attr("style", 'background:#efefef').attr("id","abc");
       //const data = [{ source : 'a', target:'b', x1 : 0, y1 : 0, x2 : 100, y2 : 100 }];

      this.drawLine(this.data);
  }


  drawLine(data){



    const svg = d3.select("#abc");
    console.log(svg)
    const line = svg.selectAll('line').data(data);
            console.log(line)
        line.enter()
        .append('line')
        .attr('stroke', '#000')
        .attr('stroke-width', 3)
        .attr('x1', function(d) {return d.x1})
        .attr('y1', function(d) {return d.y1})
        .attr('x2', function(d) {return d.x2})
        .attr('y2', function(d) {return d.y2})
        //.merge(line)

        line.exit().remove();



  }
  deleteLine() {
    d3.select('body')
    .on('keydown', () => {
            if(d3.event.keyCode === 8){
            // TODO find selected line and will delete the line in the data. 
            // currently this data is hard coded
            this.data = [{ source : 'c', target:'d', x1 : 0, y1 : 0, x2 : 100, y2 : 100 }];
          console.log(2);
          this.drawLine(this.data);
        }

    })
  }

  render() {
    return <div>
      <div id='svg'></div>
    </div>
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

1 个答案:

答案 0 :(得分:2)

您缺少key function。没有按键功能,

  

将数据中的第一个基准分配给第一个所选元素,将第二个基准分配给第二个所选元素,依此类推。通过计算每个数据和元素的字符串标识符,可以指定一个关键函数来控制将哪个数据分配给哪个元素,从而取代默认的按索引联接。

对于您而言,最好的字符串是结合sourcetarget

const line = svg.selectAll('line').data(data, function(d){
    return d.source + d.target;
});

这是更新的JSFiddle,只需按 backspace https://jsfiddle.net/31vfwcjp/1/。顺便说一下,什么都不会改变,因为您的更新选择什么也不做。

相关问题