进击的前端

学习React(二)

March 29, 2018

Components

React 组件分为函数式组件(Functional Components) 和类式组件(Class Components)。从字面意思可以看出来,组件可以写成函数形式,也可以写成类的形式。

Functional Components

index.js 文件内容:

import React from 'react'
import ReactDom from 'react-dom'

function Welcome (props) {
    return <h1>Hello, {props.name}</h1>
}

ReactDom.render(
    <Welcome name="John" />,
    document.getElementById('root')
)

Class Components

index.js 文件内容:

import React from 'react'
import ReactDom from 'react-dom'

class Welcome extends React.Component {
    constructor () {
        return <h1>Hello, {this.props.name}</h1>
    }
}

ReactDom.render(
    <Welcome name="John" />,
    document.getElementById('root')
)

index.html 文件内容:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>React Demo</title>
</head>
<body>
    <div id="root"></div>
    <script src="./index.js"></script>
</body>
</html>

Functional Components 和 Class Components 可以混用,本质上都是传入只读的 props 对象,保证数据的单向流动,React 根据 props 对象传入的内容更新渲染 DOM。


Kyle Mathews

Written by ricosmall.
Github