reactjs - 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 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用此函数而不是返回它。
提前致谢
解决方案
检查沙盒链接:
https://codesandbox.io/s/affectionate-goodall-mh0t7?file=/src/Header.js
问题出在 Header 组件上,它应该是:
const year = date.getFullYear();
代替
const year = date.getFullYear;
getFullYear 是一个函数,这就是您收到错误的原因。
推荐阅读
- css - Angular 材质网格列表排列内容到顶部
- java - 负载均衡器没有可供客户端使用的服务器:会议
- sql - ORA-01427: SELECT * FROM TABLE 给出错误单行子查询返回多于一行
- c# - C# 反编译器如何在没有 PDB 文件的情况下工作?
- python - 使用python获取二叉树中给定级别上的所有节点
- ios - UITableView 自定义单元格按钮从主视图中选择其他按钮?
- android - 我的三星平板电脑上的偏好问题,但不是我的手机,可能与上下文有关?
- python - 主管中的多个程序
- javascript - 使用 $.post 将 javascript 数组传递给 c# 数组/列表,而不将数据类型指定为 json
- java - 通过 Netbeans 使用 mysql 时出现意外错误