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;
当我尝试执行此代码时,它说“ Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it. ”我也尝试将return语句包含在div中,但它仍然会给出相同的错误 . 我是React.js的新手,所以有人可以指出一些文档或解释这个错误背后的原因以及如何解决它?我也看了类似的问题,但找不到符合我要求的东西 .
编辑:我已经编辑了我的渲染,看起来像这样
render() {
if(this.state.editing)
return this.renderForm();
else
return this.renderNormal();
}
已经解决了这个问题,但现在当我点击编辑它时会出现以下错误:
TypeError: Cannot set property 'setState' of undefined
编辑:这通过在构造函数中进行以下更改得到解决
constructor(props){
super(props);
this.state = {
editing : false,
};
this.edit = this.edit.bind(this);
this.save = this.save.bind(this);
}
1 回答
更正:
您缺少函数调用 .
if else 没有以正确的方式使用 . 相反,您可以使用三元运算符 .
render() { { this.state.editing ? this.renderForm() : this.renderNormal() } }
或使用 if - else .
edit
和save
函数中,您正在使用this
. 但是您没有将this
绑定到组件范围 .做
this
绑定要么:在构造函数中:
或使用箭头功能: