2016-08-04 9 views
2

最近私は反応を覚え始めました。リアクション動的子コンポーネント番号

私はそれはあなたがそれをクリックしたとき、それは数を持っている子要素を作成し、子の削除ボタンがあることがボタンで反応するスクリプト

var Parent = React.createClass({ 
    getInitialState: function() { 
    return {children: []}; 
    }, 
    onClick: function() { 
    var childrens = this.state.children; 
    childrens.push({ 
     name: this.props.name, 
     index: this.state.children.length + 1, 
     key: this.props.name + this.state.children.length + 1 
    }); 
    this.setState({children: childrens}); 
    }, 
    onChildMinus: function(index) { 
    var childrens = this.state.children; 
    childrens.splice(index - 1, 1); 
    this.setState({children: childrens}); 
    }, 
    render: function() { 
    return (
     <div> 
     <div className="parent" onClick={this.onClick}> 
      {this.props.name} 
      - Click Me 
     </div> 
     {this.state.children.map((child) => (<Child name={child.name} index={child.index} key={child.key} onMinusClick={this.onChildMinus}/>))} 
     </div> 
    ); 
    } 
}); 

var Child = React.createClass({ 
    getInitialState: function() { 
    return {selected: false}; 
    }, 
    onClick: function() { 
    this.setState({selected: true}); 
    }, 
    onMinusClick: function() { 
    if (typeof this.props.onMinusClick === 'function') { 
     this.props.onMinusClick(this.props.index); 
    } 
    }, 
    render: function() { 
    let classes = classNames({'child': true, 'selected': this.state.selected}); 
    return (
     <div className={classes}> 
     <span onClick={this.onClick}>{this.props.name} {this.props.index}</span> 
     <span onClick={this.onMinusClick}>Remove</span> 
     </div> 
    ) 
    } 
}); 

ReactDOM.render(
    <Parent name="test"/>, document.querySelector("#container")); 

https://jsfiddle.net/uqcxo1pg/1/

を作成しました素子。

子要素を削除すると、それは親配列から削除されますが、すべての子要素が正しい番号に更新されるようにするにはどうすればよいですか?

答えて

0

onClickに子のindexを設定しているため、前の子が削除されてもその値は更新されません。 の目的が<Child/>の場合は、onClickに割り当てられたindexではなく、配列の子のインデックスを渡すことができます。元のインデックスと注文の両方が必要な場合は、別の小物を<Child />に追加することをおすすめします。あなたはchild.indexを更新する必要がある場合

{this.state.children.map((child, index) => (
    <Child 
    name={child.name} 
    index={index} 
    key={child.key} 
    onMinusClick={this.onChildMinus} 
    /> 
))} 

https://jsfiddle.net/uqcxo1pg/2/

アップデートは

あるいは、あなたはthis.state.childrenを反復し、それらの番号を変更する必要があります。最も効率的な方法は、削除された子のインデックスから開始することですが、これは強引な代替手段です。

const renumberedChildren = this.state.children.map((child, index) => { 
    child.index = index + 1; 
    return child; 
}); 
関連する問題