React Component 创建方式

1. createClass

这个在react 15以及之前版本的唯一的方式创建组件,在16版本以后这种方法被废弃了.通过下面例子了解一下:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React15 Test Pagetitle>
head>
<body>

<div id="react-component">div>


<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.js">script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.1/react-dom.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.js">script>

<script type="text/babel">
    var MyComponent = React.createClass({
        render() {
            return <div>
                <h1>Hello world</h1>
                <p>This is my first react page</p>
            </div>
        }
    })

    ReactDOM.render(<MyComponent/>, document.getElementById("react-component"))
script>
body>
html>

2. React.Component

react 16版本提供继承React.Component完成组件的定义,例子如下:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React16 Test Pagetitle>
head>
<body>

<div id="react-component">div>


<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin>script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin>script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.js">script>

<script type="text/babel">
    class MyComponent extends React.Component{
        render() {
            return <div>
                <h1>Hello world</h1>
                <p>This is my first react page</p>
            </div>
        }
    }

    ReactDOM.render(<MyComponent/>, document.getElementById("react-component"))
script>
body>
html>

3. Stateless function

react 16支持es6的语法,使得创建Component更加方便,
例子如下:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React16 Test Pagetitle>
head>
<body>

<div id="list">div>


<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin>script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin>script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.js">script>

<script type="text/babel">
    const MyList = () => {
        return <ul>
            <li>A</li>
            <li>B</li>
        </ul>
    }
    /* 或
    const MyList = () =>
        
  • A
  • B
*/
ReactDOM.render(<MyList/>, document.getElementById("list"))
script> body> html>

你可能感兴趣的:(react)