首页 > 解决方案 > React - 函数作为 React 子级无效

问题描述

我是新手,这是我的第一个应用程序。我将一个组件内部调用到另一个组件,然后将这些函数移到 app.js

//app.js

   class App extends React.Component {
  state = {
    todos:[
      {id:1, title:'get haircut',completed: false},
      {id:2, title:'learn react',completed: false},
      {id:3, title:'chaaa',completed: false},
    ]
  }
  markComplete=(id) =>{
    this.setState({
      todos: this.state.todos.map((myTodo)=>{
        if(myTodo.id === id ){
          myTodo.completed = !myTodo.completed;
        }
        return myTodo
      })
    })
  };
  deleteTodo =(id) =>{
    this.setState({
      todos: [...this.state.todos.filter((myTodo) =>{
        return myTodo !==id
      })]
    })
  }
  render(){
  return (
    <div className="App">
      <Header/>
      <RetrivedTodos todos={this.state.todos}
      markComplete={this.markComplete}
      deleteTodo={this.deleteTodo}
      />
    </div>
  );
  }
}

//RetrivedTodos.js

class RetrivedTodos extends Component {
render () {
    return this.props.todos.map((retrivedTodos) =>(
        <TodosItems key={retrivedTodos.id} todos={retrivedTodos}
        markComplete={this.props.markComplete}
        deleteTodo={this.props.deleteTodo}
        />
    ))
}

}

//TodoItems.js

class TodosItems  extends Component {
getStrikeMark = () => {
    return {
        textDecoration:this.props.todos.Completed ? 'line-through': 'none'
    }
}
render () {
    const { id , title } = this.props.todos
    return (
        <div className='main-todos-div' style={this.getStrikeMark()}>
            <div className='todo-div'>
                <input type="checkbox" className='checkbox-round' 
                onChange={this.props.markComplete.bind(this,id)}/> 
                <span>{title}</span>
            </div>
            <div className='btn-div'>
                <button onClick={this.props.deleteTodo.bind(this,id)}>
                    <i className="fas fa-trash"></i>    
                 </button>
            </div>
        </div>
    )
}

} //标题

class Header extends Component {
render () {
    const date= new Date();
    const todayDate = date.getDate();
    const month = date.toLocaleString('default',{month:'long'});
    const year = date.getFullYear;
    const day = date.toLocaleDateString('default',{weekday:'long'});
    return(
        <div className='main-header-div'>
                <div className='background-div'> </div>
                <div className='date-month-div'> </div>
                <span>{todayDate}</span>
                <span>{month}</span>
                <span>{year}</span>
                <span>{day}</span>
                </div>
    )
}

}

这里有什么问题?它显示了这个错误

警告:函数作为 React 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用此函数而不是返回它。

提前致谢

标签: reactjsreact-nativereact-reduxreact-router

解决方案


检查沙盒链接:

https://codesandbox.io/s/affectionate-goodall-mh0t7?file=/src/Header.js

问题出在 Header 组件上,它应该是:

 const year = date.getFullYear();

代替

 const year = date.getFullYear;

getFullYear 是一个函数,这就是您收到错误的原因。


推荐阅读