3
你好,我是想传递函数子类和子类调用它,但问题也显示父函数的功能是不确定的如何调用从孩子撑起阵营15.5.0
无法读取未定义
这里财产 'removeComment' 是我的代码
父类:
import React from 'react';
import Navbar from './notes';
export default class Board extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
comments: [
'Kingyyy',
'React',
'Learning'
]
};
}
removeComment() {
console.log(i);
var arr = this.state.comments;
arr.splice(i,1);
this.setState({comments: arr});
}
editComment(newtext, i) {
console.log(i);
var arr = this.state.comments;
arr[i] = newtext;
this.setState({comments: arr});
}
addComment() {
var text = prompt('enter the new ');
var arr = this.state.comments;
arr[arr.length] = text;
this.setState({comments: arr});
}
eachComment(elem, i) {
return (
<Navbar key={i} index={i} editComment={(newtext, i) => this.editComment.bind(this)} removeComment={(i) => this.removeComment.bind(this)}>
{elem}
</Navbar>
);
}
render() {
return (
<div>
<button onClick={this.addComment} className="btn btn-success">add new comment</button>
<br />
{
this.state.comments.map(this.eachComment)
}
</div>
);
}
}
子类:
import React from 'react';
export default class Navbar extends React.Component {
edit() {
this.setState({
edit: !this.state.edit
})
}
save() {
var value = this.refs.newtext.value;
this.props.editComment(value,this.props.index);
this.setState({
edit: !this.state.edit
})
}
remove() {
this.props.removeComment(this.props.index);
}
constructor(props, context) {
super(props, context);
this.state = {edit: false};
}
normal() {
return (
<div>
<h1>{this.props.children}</h1>
<button className="btn btn-info" onClick={this.edit.bind(this)}>
edit
</button>
<button className="btn btn-danger" onClick={this.remove.bind(this)}>
remove
</button>
</div>
);
}
editing() {
return (
<div>
<textarea ref="newtext" defaultValue={this.props.children}></textarea>
<br/>
<button className="btn btn-success" onClick={this.save.bind(this)}>
save
</button>
</div>
);
}
render() {
if (this.state.edit) {
return this.editing();
} else {
return this.normal();
}
}
}
感谢您的回复但同样的概率lem和相同的错误 “不能读属性'removeComment'未定义的” –
道具是未定义的。你需要确保你的函数具有这个上下文。绑定它到你的所有功能 –
它工作后,我添加“this.eachComment = this.eachComment.bind(this);”给父构造函数谢谢 –