簡體   English   中英

點擊時無法將其他元素的ID添加到狀態數組

[英]Can't add different element's id to state array on click

我正在嘗試將svg圈子的ID設置為單擊狀態。

我希望將ID(例如1、2和3)設置為狀態數組: [1, 2, 3]

發生的是,當我單擊圓1時,數組如下所示: [1]如預期。 當我繼續並單擊圓2時,數組包含[2]而不是預期的[1, 2] 如果我繼續進行操作,然后再次單擊圓1,則數組看起來像[1, 1] 因此,數組始終包含一個或多個相同的項目,但拒絕推送不同的項目,例如[1, 3]

我嘗試使用concat,push和spread運算符將id添加到狀態數組,所有這些都具有如上所述的相同意外結果。

我在構造函數中設置了初始狀態:

constructor(props) {
    super(props);
    this.state = { array: [] };
}

並嘗試使用concat將項目添加到狀態數組:

test = (e) => {
    const currentArray = this.state.array;
    const newArray = currentArray.concat(e.currentTarget.__data__.id);
    this.setState({ array: newArray }, () => console.log(this.state.array));
};

和點差運算符:

test = (e) => {
    let newArray = this.state.array.splice();
    newArray.push(e.currentTarget.__data__.id);
    this.setState(prevState => ({
        array: [...prevState.array, newArray ]
    }), () => console.log(this.state.array));
};

這是圓元素:

<circle onClick={this.test.bind(this)}/>

我設法通過將數組設置為變量並在單擊時將id推入其中來使其工作。 但是使用React時,使用狀態來執行此操作似乎很有意義。 希望您能告訴我我做錯了什么。

更新-父組件中圓的映射:

const nodes = this.state.nodes.map( (node) => {
    return (
        <Node
            nodeClass={this.props.nodeClass}
            data={node}
            label={node.label}
            key={node.id}
        />);
    });

您沒有正確傳遞ID,您需要將test函數上移至Graph組件並創建具有array stateconstructor

然后像這樣將數據映射到SVG中

<svg className="graph" width={width}  height={height} >
              {this.props.data.nodes.map( (node) =>   
                <g  onClick={this.test.bind(this, node)}>

            <Node
                data={node}
                name={node.name}
                key={node.id}
            />
                </g>)}
                <g>
                     {this.props.data.links.map( (link,i) => 
                <Link
                    key={link.target+i}
                    data={link}

                />)}
                </g>
            </svg>

我們上面所做的重要事情是,我們使用onClick bind傳遞了節點

onClick={this.test.bind(this, node)}

然后調用測試函數,我添加了一些額外的代碼,以避免重復該單擊的ID

test = (node) => {
  console.log(node.id, 'look here this coming from test function')
  if(this.state.array.indexOf(node.id) !== -1){
     this.setState(prevState => ({ 
        array: this.state.array.filter(d => d.id !== node.id)
    }));// this will not repeat the clicked id
  }else{
      this.setState(prevState => ({ 
        array: [...prevState.array, node.id]
    }));
  }
};

這是完整的代碼

https://codepen.io/Liamm12/pen/NYeOyW?editors=0011

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM