当用户单击删除按钮时,我尝试删除子元素(注意)。删除方法位于父级(Board)上,我尝试通过 Prop 将其传递给子级,但它不起作用。
我尝试使用简单的删除,this.remove - 未定义删除,或者这个,this.remove.bind(this) 似乎不起作用;位置:eachNote(text,i) 方法
import React from 'react';
import ReactDOM from 'react-dom';
class Note extends React.Component{
constructor(props){
super(props);
this.state = {editing: false};
}
edit() {
this.setState({editing: true});
}
save() {
let val = this.refs.newText.value;
this.setState({editing: false});
}
renderNormal(){
return (
<div>
<p>{this.props.children} </p>
<button type="button" onClick={this.edit.bind(this)}>Edit</button>
<button type="button" onClick={this.hRemove.bind(this)}>Remove</button>
</div>
);
}
renderForm(){
return (
<div>
<textarea ref="newText" defaultValue={this.props.children}></textarea>
<button type="button" onClick={this.save.bind(this)}>Saved</button>
</div>
);
}
render() {
if(this.state.editing ==true ) {return this.renderForm();}
else {return this.renderNormal();}
}
}
class Board extends React.Component{
constructor(props) {
super(props);
this.state = {comments: ['icecream','antimoniu','bentrans'] };
}
remove(i){
let arr = this.state.comments;
arr.splice(i,1);
this.setState({comments: arr});
}
eachNote(text,i) {
return (<Note key={i} index={i} hRemove={this.remove}>{text}</Note>);
}
render(){
return (
<div>
{this.state.comments.map(this.eachNote)}
</div>
);
}
}
ReactDOM.render(<Board />, document.getElementById('container'));
我尝试了 Rafi Ud Daula Refat 和 Sven(感谢解答)代码以及下面的代码,但我仍然收到错误:这是未定义的;
在父级中,我有:
eachNote(text,i) {
return (<Note key={i} index={i} hRemove={this.remove.bind(i)}>{text} </Note>);
}
在 child 中,我有:
removed(i) {
this.props.hRemove(i);
}
renderNormal(){
return (
<div>
<p>{this.props.children} </p>
<button type="button" onClick= {this.edit.bind(this)}>Edit</button>
<button type="button" onClick= {this.removed.bind(this,i)}>Remove</button>
</div>
);
}
我也尝试了 this.removed.bind(this) 和 this.removed.bind(i), hRemove={this.remove.bind(i)},它们的组合不起作用
最佳答案
如果您想使用父级的一种方法,您应该将该函数作为 Prop 传递给子级。从子级开始,您可以通过以下方式访问它:
this.props.functionName
在你的笔记组件中
<button type="button" onClick={this.hRemove.bind(this)}>Remove</button>
但请注意组件没有任何名为 hRemove 的方法。可以通过
进行评估this.props.hRemove()
<button type="button" onClick={this.props.hRemove(idorsomething)}>Remove</button>
由于父组件中的“remove”函数只有一个参数。因此,从子组件注释中,您传递了变量 a。然后它就会起作用。喜欢
this.props.hRemove(id)
关于javascript - React.js 和 ES2015 - 将方法从父级传递给子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39145844/