简体   繁体   English

子组件未在父组件中正确呈现

[英]Child component is not rendered properly in the parent component

The following is the parent component: 以下是父组件:

 class Parent extends Component {
     constructor(props) {
         super(props);
         this.state = {

         }
     }

     render() {
         return (
             <div>
                 <h1>My heading</h1>
                 <child />
             </div>
         );
     }
 }

 ReactDOM.render(<Parent />, document.querySelector('.container'));

The following is the child component: 以下是子组件:

 import React from 'react';

 class child extends React.Component {
     constructor(props) {
         super(props);
         this.state = {}
     }

     render() {
         return (<p>My paragraph</p>);
     }
 }

 export default child;

I am very new to React.js so this question might be stupid. 我对React.js很陌生,所以这个问题可能很愚蠢。 But why only the parent component, namely "My heading" is displayed on the page and the child component is not shown up? 但是,为什么页面上仅显示父组件(即“我的标题”)而子组件没有显示? I expect both the parent and the child components to be displayed on the page. 我希望父级和子级组件都显示在页面上。

Also, what is the difference between: 另外,两者之间有什么区别?

1) document.querySelector('.container') ; 1) document.querySelector('。container') ;

AND

2) document.getElementById('.container') ; 2) document.getElementById('。container') ;

In my case, only 1) works and when I tried to use 2) in ReactDOM.render() , I got an error message saying that: Target container is not a DOM element. 就我而言,只有1)有效,当我尝试在ReactDOM.render()中使用2)时,我收到一条错误消息,指出:目标容器不是DOM元素。

Thank you! 谢谢!

Capitalize child to be Child . Child大写为Child Custom component classes must have capital names, which differentiates them from vanilla DOM elements. 自定义组件类必须具有大写名称,这使它们与原始DOM元素区分开。

For your second question, read the method name, getElementById . 对于第二个问题,请阅读方法名称getElementById Your container element doesn't have an ID named '.container' 您的容器元素没有名为'.container'的ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM