react 在 html 与 create-react-app 中写法对比

一、引入 js 文件

页面中 react 写法:

<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>

create-react-app 中写法:

有一个 js 文件 hello.js 内容如下:

const aa = {};
const bb = {};
exports aa;
exports bb;

现在将 hello.js 引入到 world.js 中:

import Hello from 'hello.js';
  • hello .js 为外部文件,后缀 .js 是可以省略的;
  • Hello 为该文件定义的变量,用来特指 hello.js 文件 exports 的对象。

Hello 就好好比于:

Hello = {
    aa: {},
    bb: {}
}

world.js 中要想调用 aa 对象就得使用 Hello.aa;

 

hello.js 引入到 world.js 中的另一种写法:

import Hello, {aa} from 'hello.js';

此时在 world.js 中要想调用 aa 对象就可以直接使用 aa。

{aa} 语法表示直接将 Hello 对象内部的自变量 aa 给暴露了出来。

 

二、创建组件

ES6 语法中函数可以省略 function。

render () {} 

原本应该是 

function render () {}

 

页面中 react 写法:

var HelloWorld = React.createClass({
    render: function () {
        return (
            <div>
                <h1>Hello, {this.props.name}</h1>
            </div>
        );
    }
});

create-react-app 中写法:

class HelloWorld extends Component {
    render () {
        return (
            <div>
                <h1>Hello, {this.state.name}</h1>
            </div>
        );
    }
}

export default HelloWorld; // 将 HelloWorld 给暴露出去

三、数据的类型校验

这里的数据指从外层组件传递进来的属性。

可以在 this.props 对象中获取。内部调用属性值: this.props.name

 

页面中 react 写法:

var Name = React.createClass({
    propTypes: {
        name: React.PropTypes.number
    },

    render: function () {
        return <h1>Hello, {this.props.name}</h1>
    }
});

 

create-react-app 中写法:

class Name extends Component {
    static propTypes = {
        name: PropTypes.number.required
    }

    render () {
        return <h1>Hello, {this.props.name}</h1>
    }
}

export default Name;

四、设置状态值

子组件自身可以设置状态值,但属性值只能通过外层组件传入。

内部调用状态值 this.state.liked

 

页面中 react 写法:

var LikeButton = React.createClass({
    getInitialState: function () {
        return {liked: false};
    },

    render: function () {
        var text = this.state.liked ? '喜欢' : '不喜欢';
        return <h1>你<b>{text}</b>我,点击我切换状态。</h1>
    }
});

create-react-app 中写法:
 

class LikeButton extends Component {
    constructor (props) {
        super(props);
        this.state = {
            liked: false
        }
    }

    render () {
        const text = this.state.liked;
        return <h1>你<b>{text}</b>我,点击我切换状态。</h1>
    }
}

export default LikeButton;

 

转载于:https://my.oschina.net/dkvirus/blog/909946

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值