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

前端之家收集整理的这篇文章主要介绍了react 在 html 与 create-react-app 中写法对比前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、引入 js 文件

页面中 react 写法:

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

create-react-app 中写法:

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

  1. const aa = {};
  2. const bb = {};
  3. exports aa;
  4. exports bb;

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

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

Hello 就好好比于:

  1. Hello = {
  2. aa: {},bb: {}
  3. }

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

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

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

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

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

二、创建组件

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

  1. render () {}
  2.  
  3. 原本应该是
  4.  
  5. function render () {}

页面中 react 写法:

  1. var HelloWorld = React.createClass({
  2. render: function () {
  3. return (
  4. <div>
  5. <h1>Hello,{this.props.name}</h1>
  6. </div>
  7. );
  8. }
  9. });

create-react-app 中写法:

  1. class HelloWorld extends Component {
  2. render () {
  3. return (
  4. <div>
  5. <h1>Hello,{this.state.name}</h1>
  6. </div>
  7. );
  8. }
  9. }
  10.  
  11. export default HelloWorld; // 将 HelloWorld 给暴露出去

三、数据的类型校验

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

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

页面中 react 写法:

  1. var Name = React.createClass({
  2. propTypes: {
  3. name: React.PropTypes.number
  4. },render: function () {
  5. return <h1>Hello,{this.props.name}</h1>
  6. }
  7. });

create-react-app 中写法:

  1. class Name extends Component {
  2. static propTypes = {
  3. name: PropTypes.number.required
  4. }
  5.  
  6. render () {
  7. return <h1>Hello,{this.props.name}</h1>
  8. }
  9. }
  10.  
  11. export default Name;

四、设置状态值

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

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

页面中 react 写法:

  1. var LikeButton = React.createClass({
  2. getInitialState: function () {
  3. return {liked: false};
  4. },render: function () {
  5. var text = this.state.liked ? '喜欢' : '不喜欢';
  6. return <h1>你<b>{text}</b>我,点击我切换状态。</h1>
  7. }
  8. });

create-react-app 中写法:

  1. class LikeButton extends Component {
  2. constructor (props) {
  3. super(props);
  4. this.state = {
  5. liked: false
  6. }
  7. }
  8.  
  9. render () {
  10. const text = this.state.liked;
  11. return <h1>你<b>{text}</b>我,点击我切换状态。</h1>
  12. }
  13. }
  14.  
  15. export default LikeButton;

猜你在找的React相关文章