简体   繁体   English

react.js中的未定义方法

[英]Undefined method in react.js

I've binded all of my methods in the constructor to my class. 我已经将构造函数中的所有方法绑定到了我的类。 One of them is not working properly, the console logs an undefined error. 其中之一无法正常工作,控制台记录了未定义的错误。 It is executed in a function, but I previously declared it's this keyword as a class. 它是在一个函数中执行的,但我之前曾声明它是此关键字的类。 I can not spot the problem. 我无法发现问题。 The handleRemove is the method, I'm talking about. 我正在谈论的是handleRemove方法。

import React, { Component } from 'react';


class ToDoList extends Component {
  constructor(props) {
    super(props);
    this.state = {list: [], items: ''};
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleRemove = this.handleRemove.bind(ToDoList);
  }

  handleChange(event) {
    this.setState({items: event.target.value})
    console.log(event.target.value);
  }

  handleSubmit(event) {
    this.setState({ list: [...this.state.list, this.state.items]})
    event.preventDefault();
  }

  handleRemove(event) {
    const filteredArray = this.state.list.filter(item => item !== event.target.value)
    this.setState({list: filteredArray});
  }



  render() {
    return (
    <div>
      <form onSubmit={this.handleSubmit}>
        <label>
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input onClick={this.handleSubmit}type="submit" value="Submit" />
      </form>
      <ul>
        {this.state.list.map(function(i, index){
          return(
            <li key={index}>{i}<button onClick={this.handleRemove}>X</button></li>
          )
        })}
      </ul>
      <p>Remaining: {this.state.list.length}</p>
      </div>
    );
  }
}

export default ToDoList;

You are binding the method to the class , not the instance - the class does not have a static method named handleRemove , and even if it did - you can not access this within a static method; 您将方法绑定到class ,而不是instance -该类没有名为handleRemovestatic方法,即使这样做,也无法在静态方法中访问this therefore this will not work: 因此,这将不起作用:

this.handleRemove = this.handleRemove.bind(ToDoList);

Change to: 改成:

this.handleRemove = this.handleRemove.bind(this);

Two things: 两件事情:

First, in your constructor, bind this and not ToDoList . 首先,在您的构造函数中, this绑定而不是ToDoList

this.handleRemove = this.handleRemove.bind(this);

Second, functions are scoped, so inside the .map this is not the component. 其次, functions是作用域的,因此在.map this不是组件。 You can fix that by using an arrow function (or alternatively using .bind(this) ): 您可以使用箭头功能(或使用.bind(this) )解决此问题:

{this.state.list.map((i, index) => (
  <li key={index}>{i}<button onClick={this.handleRemove}>X</button></li>
))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM