无法将函数传递给 ReactJS 中的子组件

时间:2020-12-31 11:44:55

标签: reactjs react-props

我有 2 个文件。

App.js

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: ToDoData,
    };
  }

  handleChange(id) {
    console.log("changed", id);
  }

  render() {
    const ToDoItems = this.state.todos.map(function (content) {
      return (
        <ToDoItem
          key={content.id}
          content={content}
          handleChange={this.handleChange}
        />
      );
    });

    return <div>{ToDoItems}</div>;
  }
}

和 ToDoitem.js

function ToDoItem(props) {
  console.log(props);
  return (
    <label className="container">
      <input
        type="checkbox"
        checked={props.content.is_complete}
        onChange={() => props.handleChange(props.content.id)}
      />
      {props.content.title}
      <br />
    </label>
  );
}

它说

<块引用>

TypeError: 无法读取未定义的属性“handleChange”

  20 |     <ToDoItem
  21 |       key={content.id}
  22 |       content={content}
> 23 |       handleChange={this.handleChange}
     | ^  24 |     />
  25 |   );
  26 | });

我正在学习教程,完全相同的代码适用于他们,但不适用于我。我哪里做错了?

2 个答案:

答案 0 :(得分:3)

这似乎是一个范围问题 - 经典的 JS“这个”困境。

尝试交换:

const ToDoItems = this.state.todos.map(function (content) {

const ToDoItems = this.state.todos.map((content) => {

这种方法将使“this”保持在范围内

答案 1 :(得分:2)

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: ToDoData,
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(id) {
    console.log("changed", id);
  }

  render() {
    const _this = this;
    const ToDoItems = this.state.todos.map(function (content) {
      return (
        <ToDoItem
          key={content.id}
          content={content}
          handleChange={_this.handleChange}
        />
      );
    });

    return <div>{ToDoItems}</div>;
  }
}

您需要添加 this.handleChange = this.handleChange.bind(this) 并将其保存到 _this 变量中,因为无法在回调中访问它。