[英]how to add function on event onclick on array.map in react js
class ProjectFirestoreData extends Component {
constructor(props) {
super(props);
this.userDelete = this.userDelete.bind(this)
}
userDelete(authorId){
console.log(authorId)
}
render() {
let {firestore} = this.props;
if(!Array.isArray(firestore) || !firestore.length ){
return (
<div>
<h1>Loading</h1>
</div>
)
}
else{
return (
<div className="col-md-8">
<div className="row">
{
firestore.map(function(index, elem) {
return (
<div className="col-md-6 p-3" key={index.name} >
<div className="card">
<img className="card-img-top" src="..." alt="Card" />
<div className="card-body">
<h5 className="card-title text-dark">AuthorName is : {index.authorFirstName} </h5>
<p className="card-text text-dark">Some quick example text to build on the card title and make up the bulk of the card's content.
</p>
<Link to={`/userdetails/${index.authorId}`} className="btn btn-primary">Show Full Data</Link>
<button type="button" class="btn btn-dark" onClick={() => this.userDelete(index.authorId)}>Dark</button>
</div>
</div>
</div>
)
})
}
</div>
</div>
)
}
}
}
通过将常规函数传递给map
您会丢失this
上下文(常规函数的this
引用当前函数),并且由于您的userDelete
函数在map
回调函数之外,因此userDelete
未定义,如果您将map
回调函数更改为您保留类的this
范围的箭头函数因此userDelete
仍在范围内。
将firestore.map(function(index, elem) {
更改为firestore.map((index, elem) => {
这应该保持正确的this
范围。
onclick event inside map--------------- working fine for me
<div className={styles.file_content_show}>
{this.state.fileinformation.map((item)=>{
return (
<p className={styles.file_name_show}>{item.file_name}
<span className={styles.file_size_date}> ({item.file_size} | {item.file_modified_date}) <img src={attachmentdelete_logo} className={styles.attachmentdelete_logo} onClick={this.deleteattachment.bind(item.file_size)}/></span>
</p>
);
})}
</div>
function is this-------------------
@autobind
private deleteattachment(file){
var a=file;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.