作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我只贴出组件的代码:
class AddPostForm extends React.Component {
createPost(event) {
event.preventDefault();
let post = {
title : this.refs.title.value,
name : this.refs.name.value,
desc : this.refs.desc.value,
image : this.refs.image.value
}
this.props.addPost(post);
this.refs.postForm.reset();
}
render() {
return (
<div className="callout secondary form-area">
<h5>Add a Post to the React Blog</h5>
<form className="post-edit" ref="postForm" onSubmit={this.createPost}>
<label>Post Title
<input type="text" ref="title" placeholder="Post Title" required/>
</label>
<label>Author Name
<input type="text" ref="name" placeholder="Full Name required" required/>
</label>
<label>Post Body
<textarea
ref="desc"
placeholder="Write your post here" required/>
</label>
<label>Image URL - <span className="highlight">use this one to test 'http://bit.ly/1P9prpc'</span>
<input type="url" ref="image" placeholder="The URL of the featured image for your post" required/>
</label>
<button type="submit" className="button">Add Post</button>
</form>
</div>
)
}
}
当函数 createPost
被触发时,控制台会记录一个错误:Uncaught TypeError: Cannot read property 'refs' of null。
然而,当我将代码转换回 ES5 时,它起作用了:
var AddPostForm = React.createClass({
createPost : function(event) {
event.preventDefault();
// take the data from the form and create an object
var post = {
title : this.refs.title.value,
name : this.refs.name.value,
desc : this.refs.desc.value,
image : this.refs.image.value
}
// add the post to the App State
this.props.addPost(post);
this.refs.postForm.reset();
},
render : function() {
return (
<div className="callout secondary form-area">
<h5>Add a Post to the React Blog</h5>
<form className="post-edit" ref="postForm" onSubmit={this.createPost}>
<label>Post Title
<input type="text" ref="title" placeholder="Post Title" required/>
</label>
<label>Author Name
<input type="text" ref="name" placeholder="Full Name required" required/>
</label>
<label>Post Body
<textarea
ref="desc"
placeholder="Write your post here" required/>
</label>
<label>Image URL - <span className="highlight">use this one to test 'http://bit.ly/1P9prpc'</span>
<input type="url" ref="image" placeholder="The URL of the featured image for your post" required/>
</label>
<button type="submit" class="button">Add Post</button>
</form>
</div>
)
}
});
最佳答案
你应该为 createPost
设置 this
,因为 React 中的 ES2015
类没有 autobinding
, 但是当你使用 React.createClass
class AddPostForm extends React.Component {
constructor(props) {
super(props);
this.createPost = this.createPost.bind(this);
}
....
}
关于javascript - react 应用程序错误 : `Uncaught TypeError: Cannot read property ' refs' of null`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35498023/
我是一名优秀的程序员,十分优秀!