React中的组件语法

时间:2019-02-13 12:13:02

标签: reactjs

我是React的初学者,只是一些关于组件的问题 假设我有一个组件:

function HelloWorld() {
    return React.createElement('div', {}, 'Hello World!')
}

所以我的问题是:

1- HelloWorld是组件名称,不是吗?

2-然后我有下面的代码:

ReactDOM.render(
    <HelloWorld/>, document.querySelector('#root')
); 

<ComponentName/>的语法是什么?拥有render函数不是更明智的做法:

ReactDOM.render(
    HelloWorld(), document.querySelector('#root')
); 

3 个答案:

答案 0 :(得分:1)

ReactDOM.render的语法:

ReactDOM.render( <Component />, id of DOM element where component will render ); 

React中有两种类型的组件:

  • 1)功能组件(也称为无状态组件)
  • 2)类组件(也称为有状态组件

功能组件示例:

function HelloWorld() {
    return React.createElement('div', {}, 'Hello World!')
}

or 

const HelloWorld=()=>{
    return (<div>HelloWorld</div>);
}
export default HelloWorld;

类组件的示例:

class HelloWorld extends React.Component{
   render(){
      return (<div>HelloWorld</div>);
   }
}

这样传递组件:

ReactDOM.render(
    HelloWorld(), document.querySelector('#root')
); 

不是正确的方法,在React中,您将Component用作<ComponentName />

所以这就是为什么您必须像这样通过

ReactDOM.render(
        <HelloWorld/>, document.querySelector('#root')
 ); 

答案 1 :(得分:0)

1-不,这就是您正在创建的div标记的内容(又名“子代”)。那就是<div>Hello World!</div>

2-不知道您所指的ComponentName是什么。该代码段采用HelloWorld React组件并将其安装到DOM,DOM也将启动Reconciliation process

此外,JSX的目的是拥有尽可能类似于HTML的语法糖。是的,您的建议基本上是幕后发生的事情(从伪代码的角度来看),但会破坏使用JSX的目的。

答案 2 :(得分:0)

当react构建您的应用并运行时,它将类似于您给出的最后一个示例。

将所有组件反应编译为

React.createElement('htmlTag' || someOtherComponent(), ...);

因此,许多人发现使用JSX sintax编写组件更加容易和高效,而仅使用build命令来编译和捆绑代码。