简体   繁体   English

就我而言,react.js 中的奇怪状态行为

[英]Strange state behavior in react.js in my case

http://jsfiddle.net/1erw4fba/5/ 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.假设它只有在 isEditing 的状态为真时才会出现。 Then I try to purposely set that to false, but still it appear.然后我尝试故意将其设置为 false,但它仍然出现。 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.您将 onClick 放在 div 中,因此当您按下 Edit 按钮或 Delete 按钮时,它都会被调用。 Just use:只需使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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