在React中调用子组件上的事件

时间:2018-01-19 19:21:50

标签: reactjs

我有如下定义的父子组件关系:

import React, { Component } from 'react';

export class TodoList extends Component {

  constructor(props) {
    super(props)

    this.state = {
      tasks : []
    }

    this.addTask = this.addTask.bind(this)
  }

  addTask() {

      let tasks = this.state.tasks
      let title = this.textInput.value

      tasks.push({title:title})
      this.state.tasks = tasks
      this.setState({
        tasks : tasks
      })

      console.log(this.state)
  }

  render()  {

    return (
      <div>
        <input type="text" ref={(input) => {this.textInput = input}}  />
        <button onClick={this.addTask}>Add New Task</button>

        <h6>Pending Tasks</h6>
        <PendingTaskList tasks = {this.state.tasks} />

      </div>
    )
  }
}

export class PendingTaskList extends Component {

  constructor(props) {
    super(props)

    this.markAsCompleted = this.markAsCompleted.bind(this)
  }

  markAsCompleted() {
    console.log("mark as completed")
  }

  render() {

    const listItems = this.props.tasks.map(function(task){
        return <div>
                  <input type="checkbox" onChange={this.markAsCompleted} />
                  <li>
                  {task.title}
                  </li>
                  <button>Remove</button>
               </div>
    })

    return (

          <ul>{listItems}</ul>
    )
  }

}

在PendingTaskList组件中,我想调用markAsComplete事件。我怎样才能做到这一点?当我运行上面的代码时,我收到以下错误:

无法读取属性&#39; markAsCompleted&#39;未定义的

0 个答案:

没有答案