【发布时间】:2018-08-13 22:45:52
【问题描述】:
import React, { Component } from 'react';
class Comment extends Component {
constructor(props) {
super(props);
this.state = {
editing: false,
};
}
edit() {
this.setState = { editing: true };
}
remove() {
this.props.deleteFromBoard(this.props.index);
}
save() {
this.props.updateCommentText(this.refs.newText.value, this.props.index);
this.setState = { editing: false }
}
renderNormal() {
return (
<div className="commentContainer">
<div className="commentText>">{this.props.children}</div>
<button onClick={this.edit} className="button-primary">Edit
</button>
<button onClick={this.remove} className="button-danger">Remove
</button>
</div>
);
}
renderForm() {
return (
<div className="commentContainer">
<textarea ref="newText" defaultValue={this.props.children}>
</textarea>
<button onClick={this.save} className="button-success">Save
</button>
</div>
);
}
render() {
if (this.state.editing)
return this.renderForm;
else
return this.renderNormal;
}
}
export default Comment;
当我尝试执行此代码时,它说“函数作为 React 子级无效。如果您返回组件而不是从渲染中返回,则可能会发生这种情况。或者您可能打算调用此函数而不是return it." 我也尝试将 return 语句包含在 div 中,但它仍然给出相同的错误。我是 React.js 的新手,所以有人可以指出一些文档或解释这个错误背后的原因以及如何解决它?我也查看了类似的问题,但找不到符合我要求的内容。
编辑:我已将渲染编辑为如下所示
render() {
if(this.state.editing)
return this.renderForm();
else
return this.renderNormal();
}
这已经解决了这个问题,但现在当我点击编辑时,它给出了以下错误:
TypeError:无法设置未定义的属性“setState”
编辑:通过在构造函数中进行以下更改解决了这个问题
constructor(props){
super(props);
this.state = {
editing : false,
};
this.edit = this.edit.bind(this);
this.save = this.save.bind(this);
}
【问题讨论】:
标签: reactjs es6-class setstate