gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'props' of null in React Class

转载 作者:行者123 更新时间:2023-11-30 15:43:37 28 4
gpt4 key购买 nike

<分区>

我已经重构了一个组件并且我不再在类方法中使用 React.createClass 但我现在有这个错误

{this.props.removeComment.bind(null, this.props.params.svgId, i)}

TypeError: Cannot read property 'props' of undefined

代码完美运行

重构前

import React from 'react';

const Comments = React.createClass({
renderComment(comment, i) {
return (
<div className="comment" key={i}>
<p>
<strong>{comment.user}</strong>
{comment.text}
<button className="remove-comment" onClick={this.props.removeComment.bind(null, this.props.params.svgId, i)}>&times;</button>
</p>
</div>
)
},

handleSubmit(e) {
e.preventDefault();
const { svgId } = this.props.params;
const author = this.refs.author.value;
const comment = this.refs.comment.value;
this.props.addComment(svgId, author, comment);
this.refs.commentForm.reset();
},

render() {
return (
<div className="comments">
{this.props.svgComments.map(this.renderComment)}
<form ref="commentForm" className="comment-form" onSubmit={this.handleSubmit}>
<input type="text" ref="author" placeholder="author"/>
<input type="text" ref="comment" placeholder="comment"/>
<input type="submit" hidden />
</form>
</div>
)
}
});

export default Comments;

重构之后

import React from 'react';

export default class Comments extends React.Component {
renderComment(comment, i) {
return (
<div className="comment" key={i}>
<p>
<strong>{comment.user}</strong>
{comment.text}
<button className="remove-comment" onClick={this.props.removeComment.bind(null, this.props.params.svgId, i)}>&times;</button>
</p>
</div>
)
};

handleSubmit(e) {
e.preventDefault();
const { svgId } = this.props.params;
const author = this.refs.author.value;
const comment = this.refs.comment.value;
this.props.addComment(svgId, author, comment);
this.refs.commentForm.reset();
};

render() {
return (
<div className="comments">
{this.props.svgComments.map(this.renderComment)}
<form ref="commentForm" className="comment-form" onSubmit={this.handleSubmit}>
<input type="text" ref="author" placeholder="author"/>
<input type="text" ref="comment" placeholder="comment"/>
<input type="submit" hidden />
</form>
</div>
)
}
};

那么我如何在类构造函数中手动绑定(bind) this 呢?

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