代码之家  ›  专栏  ›  技术社区  ›  Teresa Salil

无法读取onClick中“someFunction”的null属性“someFunction”

  •  0
  • Teresa Salil  · 技术社区  · 7 年前

    相关代码:

    constructor(props){
        // Pass props to parent class
        super(props);
    
        this.removeItem = this.removeItem.bind(this);
        this.getList = this.getList.bind(this); 
        ...
    }
    
    removeItem(key) {
        this.ref(key).remove()
    }
    
    getList() {
        var list = []
        this.ref.on("value", function (snapshot) {
            for (var key in snapshot.val()) {
                list.push(<div class="todo-item">{snapshot.val()[key]} <button onClick={() => this.removeItem(key)}> X </button> </div>)
            }
        }, function (error) {
            console.log("Error: " + error.code);
        });
        return(list)
    }
    
    render() {
        return (
            <div class="todolist">
                .....
                {this.getList()}
            </div>
        )
    }
    

    项目列表及其“移除”按钮呈现良好效果。但是,当单击“删除”按钮时,我得到一个 TypeError: Cannot read property 'removeItem' of null

    作为 removeItem 是的函数 this ,我想 这 未正确绑定,因此 null .

    但是,我绑定了这两个函数 移除项目 和 getList

    1 回复  |  直到 7 年前
        1
  •  2
  •   Anand Undavia    7 年前

    context 什么时候迷路 this

    为了避开这个问题,

    使用箭头功能:

    this.ref.on("value", (snapshot) => { ... }, (error) => { ... });
    

    或
    使用 bind(this)

    this.ref.on("value", function (snapshot) { ... }.bind(this), function (error) { ... }.bind(this));