简体   繁体   中英

React - Functions are not valid as React child

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>
    );
  }
}

Like this everything renders but if I put {this.passingTodos} nothing renders and I get the warning in the title. I'm not entirely sure why.

Firstly you need to return the result from passingTodos method and secondly you need to invoke it in render

    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>
            )
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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