我有以下反应组件:
export default class MyComponent extends React.Component { onSubmit(e) { e.preventDefault(); var title = this.title; console.log(title); } render(){ return ( ... <form className="form-horizontal"> ... <input type="text" className="form-control" ref={(c) => this.title = c} name="title" /> ... </form> ... <button type="button" onClick={this.onSubmit} className="btn">Save</button> ... ); } };
控制台给了我undefined- 任何想法这段代码有什么问题?
undefined
您应该使用 MyComponent 类下的构造函数 extends React.Component
constructor(props){ super(props); this.onSubmit = this.onSubmit.bind(this); }
然后你会得到title的结果