2017-01-28 92 views
1

當用戶單擊提交按鈕時,我需要將這些輸入字段綁定到Message接口的實例,爲此,我在類
中創建了一個Message對象,並設置了輸入表單中的值(keepNameUpdated())。「this」在React組件事件處理程序中未定義

當我輸入的東西,它拋出

Uncaught TypeError: Cannot read property 'message' of undefined

所以它說:「這」是不確定的,但爲什麼呢?

這裏是我的代碼:

 export class IMessage { 
      Name: string; 
      Surname: string; 
     } 



    export default class Contact extends React.Component<IContactProperties, IWebPartState> { 
     message : IMessage; 
     constructor(props: IContactProperties, state: IWebPartState) { 
      super(props); 
      this.message = new IMessage(); 
     } 
public render(): JSX.Element { 
      return (
       <div className="row"> 
        <div className="form-group col-md-6"> 
         <label >Name</label> 
         <input type="text" className="form-control" onChange={this.keepNameUpdated} id="name" placeholder="Adiniz" /> 
         </div> 
         <div className="form-group col-md-6"> 
         <label >Surname</label> 
         <input type="text" className="form-control" id="surname" placeholder="Soyadiniz" /> 
         </div> 
         <div className="form-group col-md-12"> 
         <button type="button" className="btn btn-success" onClick={this.clickSubmit}><i className="fa fa-save"></i> Submit</button> 
         </div> 
        </div> 
       ); 
    } 

     private keepNameUpdated(e) { 
      this.message.Name=e.target.value; 
      } 
      private keepSurnameUpdated(e) { 
      this.message.Surname=e.target.value; 
      } 

爲什麼這個參考未定義,? enter image description here

+0

位。渲染函數在哪裏? – x0n

+0

我很簡單,這個返回jsx元素方法actualy屬於渲染功能 – TyForHelpDude

+0

比完整不完整:) – x0n

回答

1

IIRC,您必須綁定處理函數,以便他們的this的概念引用React組件的實例。所以,在你的構造函數中添加這些行:

this.keepNameUpdated = this.keepNameUpdated.bind(this); this.keepSurnameUpdated = this.keepSurnameUpdated.bind(this);

來源:缺少代碼https://facebook.github.io/react/

+0

是的它看起來解決了我的問題,但爲什麼我必須明確指定它?如果我有100個物業怎麼辦? – TyForHelpDude

+1

這只是事件處理程序在JavaScript和瀏覽器DOM中工作的方式。我不知道React足夠好來幫助你,但是也許在框架中有一些幫助函數可以幫你做...閱讀更多文檔:) – x0n

相關問題