2016-02-27 43 views
0

我正在使用Meteor和React。考慮下面這個簡單的組件。有一個本地迷你Mongo收集CommentsCollection。當componentWillMount將被調用時,組件將在其中插入一行。 getMeteorData將返回集合中的第一條記錄,我們將能夠修改標題。問題:如果我將光標置於標題的開頭並開始輸入,在更新第一個字符後,光標將跳轉到字符串的末尾,其餘的輸入將放在那裏。我如何解決這個問題?更新模型值onChange in Meteor + React將光標置於字符串末尾

CommentsCollection = new Meteor.Collection(null); // Local mini-mongo collection 
EventTestComponent = React.createClass({ 
mixins : [ReactMeteorData], 
    componentWillMount(){ 
     CommentsCollection.insert({title:"test title", message:"some test message"}); 
    }, 
    getMeteorData(){ 
     return { 
      comment: CommentsCollection.findOne() 
     }; 
    }, 

    handleTitleChange(e){ 
     CommentsCollection.update({_id: this.data.comment._id}, {$set:{title: e.target.value}}); 
    }, 
    render(){ 
     if(this.data.comment) { 
      return (
       <div> 
        <input type="text" value={this.data.comment.title} onChange={this.handleTitleChange}/> 
       </div> 
      ); 
     }else{ 
      return <div>Loading...</div> 
     } 
    } 
}); 

回答

1

我想出了這個解決方案之後我張貼的問題:

<input type="text" 
          defaultValue={this.data.comment.title} 
          onKeyUp={this.handleTitleChange}/> 

所以:改變valuedefaultValue,並onChangeonKeyUp。奇蹟般有效!