首页 > 解决方案 > 函数作为 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);

标签: reactjs

解决方案


如果你想渲染 JSX,

  1. 您必须调用函数,例如this.Header()this.Header函数引用不调用它。

  2. 你必须返回结果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>


推荐阅读