如何在react js中的array.map上的事件onclick上添加函数

sam*_*ali 1 javascript reactjs

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>
                )
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

onclick 事件在 array.map 之后起作用,但在 array.map 下不起作用有什么方法可以实现它吗?我尝试过添加

<button type="button" class="btn btn-dark" onClick={() =>this.userDelete(index.authorId)}>Dark</button>
Run Code Online (Sandbox Code Playgroud)

在 array.map 之后,它工作正常。但在 array.map 下它不起作用。错误说

类型错误:无法读取未定义的属性“userDelete”

Shm*_*uer 5

通过将常规函数传递给您,map您会丢失上下文this(常规函数this对当前函数的引用),并且由于您的函数位于回调函数userDelete之外,所以未定义,如果您将回调函数更改为箭头函数,您将保留作用域因此该类仍在范围内。mapuserDeletemapthisuserDelete

firestore.map(function(index, elem) {对此进行更改firestore.map((index, elem) => {应保持适当的this范围。