gpt4 book ai didi

javascript - react 应用程序错误 : `Uncaught TypeError: Cannot read property ' refs' of null`

转载 作者:搜寻专家 更新时间:2023-11-01 04:48:22 24 4
gpt4 key购买 nike

我只贴出组件的代码:

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

....
}

Autobinding

关于javascript - react 应用程序错误 : `Uncaught TypeError: Cannot read property ' refs' of null`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35498023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com