基于类的组件无法在ReactJs应用程序中按预期方式工作

问题描述

我正在尝试在功能组件的一部分中显示基于类的组件的内容,但是它不起作用。 基于类的组件:

class commentForm extends Component {
    render() {
        return(
            <div>
                <h1>Hello</h1>
                <Button class="btn btn-light"><span className="fa fa-comment-o"></span> Submit 
                comment</Button>
            </div>
        );
    }
}

功能组件:

function RenderComments({comments})
{
    if(comments!=null)
    {
        return (
            <div className="col-12 col-md-5 m-1">
                <h4>Comments</h4>
                <ul className="list-unstyled">
                    {comments.map((comment)=>{
                        return(
                            <li key={comment.id}>
                                <p>{comment.comment}</p>
                        <p>-- {comment.author},{new Intl.DateTimeFormat('en-US',{ year: 'numeric',month: 'short',day:'2-digit' }).format(new Date(Date.parse(comment.date)))}</p>
                            </li>
                        );
                    })}
                </ul>                
                <commentForm />
                {commentForm}
            </div>
        )
    }
    else{
        return(
            <div></div>
        );
    }
}

在这里,我想显示来自RenderComments的commentForm的内容。我没有收到任何错误,但是代码没有在前端显示commentForm的内容

解决方法

您应该以大写字母开头来命名组件,commentForm应该重命名为class CommentForm extends Component {}

形成React docs

当元素类型时,用户定义的组件必须大写 以小写字母开头,它表示内置组件,例如 <div><span>并导致将字符串“ div”或“ span”传递给 React.createElement。以大写字母开头的类型,例如编译为React.createElement(Foo)并对应于组件 在您的JavaScript文件中定义或导入。

我们建议使用大写字母命名组件。如果你有一个 以小写字母开头的组件,请将其分配给 在JSX中使用大写变量之前。