"this" 在 React 组件事件处理程序中未定义

"this" undefined in React component event handler

当用户单击提交按钮时,我需要将这些输入字段绑定到 Message 接口的一个实例,为此我在 class
中创建了一个 Message 对象 并在 form(keepNameUpdated()) 中设置输入值的值。

当我输入内容时它会抛出

Uncaught TypeError: Cannot read property 'message' of undefined

所以它说 "this" 未定义,但为什么?

这是我的代码:

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

为什么这个引用是未定义的?

IIRC,您必须绑定处理函数,以便它们的 this 概念引用 React 组件的实例。因此,在您的构造函数中,添加以下行:

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

来源:https://facebook.github.io/react/