简体   繁体   中英

Strange state behavior in react.js in my case

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>
      )
   }
})

When I click delete button, why the edit input text appear? suppose it will only appear if the state of isEditing is true. Then I try to purposely set that to false, but still it appear. This is unusual to me.

Your problem is here:

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

You put the onClick in the div, so it's called both when you press the Edit button or the Delete button. Just use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM