React-函数作为React子代无效

时间:2019-01-09 05:45:33

标签: javascript reactjs

class TodoList extends React.Component {
  constructor(props) {
    super(props);
  }

  passingTodos = () => {
    this.props.todos.map(item => {
      return <TodoItem key={item.id} todo={item} deleteTodo={this.props.deleteTodo} />;
    });
  };

  render() {
    return (
      <div className="todoList">
        <h1>Todo List</h1>
        <div className="todo-items">
          {this.props.todos.map(item => {
            return <TodoItem key={item.id} todo={item} deleteTodo={this.props.deleteTodo} />;
          })}
        </div>
      </div>
    );
  }
}

就像这样,所有内容都会渲染,但是如果我放置{this.passingTodos},则什么都不会渲染,并且标题中会出现警告。我不确定为什么。

1 个答案:

答案 0 :(得分:1)

首先,您需要从passingTodos方法返回结果,然后第二,需要在渲染器中调用它

    class TodoList extends React.Component{
        constructor(props){
            super(props)
        }

        passingTodos = () => { 
             return this.props.todos.map( (item) => {
                return <TodoItem key={item.id} todo = {item} deleteTodo = {this.props.deleteTodo}/>
            })
        }

        render(){
            return(
                <div className = "todoList">
                <h1>Todo List</h1>
                <div className = "todo-items">
                    {this.passingTodos()}
                </div>
            </div>
            )
        }
    }