reactjs - 函数作为 React 子级无效。如果您返回 Component 而不是从渲染
问题描述
我想在我的页面上显示发送的帖子,但它有一个错误:
函数作为 React 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用此函数而不是返回它。
代码如下:
import React, { Component } from 'react';
import { render } from 'react-dom';
const rootNode = document.getElementById('root');
class Blog extends Component {
constructor(props) {
super(props);
this.Header = this.Header.bind(this);
this.UnderHeader = this.UnderHeader.bind(this);
}
Header() {
this.props.posts.map(post => <li key={post.id}>{post.title}</li>);
}
UnderHeader() {
this.props.posts.map(post => {
return (
<div key={post.id}>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
});
}
render() {
return (
<div>
<ul>{this.Header}</ul>
<hr />
{this.UnderHeader}
</div>
);
}
}
const posts = [
{ id: 1, title: 'title1', content: 'content1' },
{ id: 2, title: 'title2', content: 'content2' },
{ id: 3, title: 'title3', content: 'content3' },
{ id: 4, title: 'title4', content: 'content4' }
];
render(<Blog posts={posts} />, rootNode);
解决方案
如果你想渲染 JSX,
您必须调用函数,例如
this.Header()
,this.Header
函数引用不调用它。你必须返回结果
map
,`map 返回一个需要从函数返回的 JSX 组件数组。
代码:
const { Component } = React;
const { render } = ReactDOM;
const rootNode = document.getElementById('root');
class Blog extends Component{
constructor(props){
super(props)
this.Header=this.Header.bind(this)
this.UnderHeader=this.UnderHeader.bind(this)
}
Header(){
return this.props.posts.map((post)=><li key={post.id}>{post.title}</li>)
}
UnderHeader(){
return this.props.posts.map((post)=>{
return(
<div key={post.id}>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
)
})
}
render(){
return(
<div>
<ul>
{this.Header()}
</ul>
<hr/>
{this.UnderHeader()}
</div>
)
}
}
const posts =[
{id :1 ,title :'title1' ,content :'content1'},
{id :2 ,title :'title2' ,content :'content2'},
{id :3 ,title :'title3' ,content :'content3'},
{id :4 ,title :'title4' ,content :'content4'},
]
render(
<Blog posts ={posts}/>,
rootNode
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
推荐阅读
- pug - Nodemailer pug 使用每个迭代数组
- python - Matplotlib 图挂在 threading.Thread.join() 被使用
- botframework - 如何从 Microsoft Teams Bot 获取用户数据一次
- ios - UIControl 在 UITableView Cell 内没有收到触摸
- python - Python Href 抓取
- shiny - 将服务器文件转换为 HTML
- excel - EXCEL连接两个边框之间的单元格中的所有文本
- arrays - PowerShell:将十六进制变量转换为单个(float32)大端变量
- python - 检查数据框中的多个字段(字符串字段和日期字段)
- api - 在地图上显示 3D 建筑物