[英]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.