2016-10-05 48 views
-1

http://jsfiddle.net/1erw4fba/5/奇怪的國家行爲

var App = React.createClass({ 
    getInitialState(){ 
    return { 
    items:[1,2,3], 
    isEditing:false 
    } 
    }, 
    dlt_item(key){ 
    var newItems = this.state.items.filter((item,i)=> i !== key) 
    this.setState({items:newItems,isEditing:false}) 
    }, 
    edit_handler(){ 
    this.setState({isEditing:true}) 
    }, 
    isEditing_html(){ 
    return(
    <div> 
    <input type="text" /> 
    <button>Save</button> 
    </div> 
    ) 
    }, 
    renderItem(){ 

    return(

     this.state.items.map(function(item,i) { 

     var temp = null; 
     if(this.state.isEditing){ 
    temp = this.isEditing_html() 
    }else{ 
    temp = <div onClick={this.edit_handler}><button>Edit</button> 
    <button onClick={this.dlt_item.bind(this,i)}>Delete</button></div> 
    } 
     return (<li key={i}>{item} 
    &nbsp; 
    {temp} 
    </li> 

    ) 
    }.bind(this) 
    ) 
    ) 
    }, 
    render(){ 
     return(
     <ul> 
     {this.renderItem()} 
     </ul> 
    ) 
    } 
}) 

當我點擊刪除按鈕,爲什麼編輯輸入文本出現?假設它只會在isEditing的狀態爲true時出現。然後我試圖故意將其設置爲假,但它仍然出現。這對我來說很不尋常。

回答

1

你的問題是在這裏:

temp = <div onClick={this.edit_handler}><button>Edit</button> 
<button onClick={this.dlt_item.bind(this,i)}>Delete</button></div> 

你把的onClick在div,因此它被稱爲既當您按下編輯按鈕或刪除按鈕。只需使用:

temp = <div><button onClick={this.edit_handler}>Edit</button> 
<button onClick={this.dlt_item.bind(this,i)}>Delete</button></div>