如何解决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',{id:3,title:'chaaa',]
}
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子元素无效。如果发生这种情况 您返回一个Component而不是从render返回。或许 您打算调用此函数而不是返回它。
预先感谢
解决方法
检查沙盒链接:
https://codesandbox.io/s/affectionate-goodall-mh0t7?file=/src/Header.js
问题出在Header componentnt上,应该是:
const year = date.getFullYear();
代替
const year = date.getFullYear;
getFullYear是一个函数,这就是您收到错误的原因。
, RetrivedTodos
对我来说似乎无效。您将返回一个映射函数,而不是一个React组件。此映射函数应在返回值内部执行,而不是返回值本身。
这是它的外观:
class RetrivedTodos extends Component {
render () {
return (
<div>
{this.props.todos.map((retrivedTodos) => (
<TodosItems key={retrivedTodos.id} todos={retrivedTodos}
markComplete={this.props.markComplete}
deleteTodo={this.props.deleteTodo}
/>
))
}
</div>
)
}
编辑:在Header
中,您将返回一个函数而不是它的值:
const year = date.getFullYear;
应该是:
const year = date.getFullYear();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。