react语法 - 给vue开发者

Dva - react状态管理 - 给vuex开发者
React Router 5.x - 给vuex开发者
Redux - 给vue开发者

根节点起始(Hook写法在下面)

create-react-app my-app
// 使用typescript
create-react-app my-app --template typescript
ReactDOM.render(<h1>Hello, world!</h1>, document.getElementById("root"));
// 组件
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>现在是 {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(<Clock date="new Date()" />, document.getElementById("root"));

差别对照表

VUE react
beforeMount(created?) componentWillMount
mounted componentDidMount
beforeDestroy componentWillUnmount
data state (无双向绑定,需要 this.setState({})来更新视图)
props props
slot props(.children 为默认 slot,具名 slot 被当做一般属性传入)
$refs refs
@click="fn" onClick={this.fn} (fn 最好为剪头函数)
v-model 没有,自己实现
:class="{active: true}" className={"active"} (仅字符串)
:style="{color:'red'}" style={{color:'red'}}) (可对象)

没有@:,大括号是一切。下面详细说:

使用组件

props 无需声名,直接使用;需要对其进行格式验证时,可以使用 propTypes

class Welcome extends React.Component {
  //propTypes: {   非必要
  //  name: React.PropTypes.string.isRequired,
  //},

  render(props) {
    return (
      <div>
        <h1>Hello {props.name}!</h1>
        {props.children}   <!-- slot -->
        {props.left}   <!-- slot name="left"  -->
      </div>
    );
  }
}

ReactDOM.render(
    <HelloMessage name="Vue" left={ <em /> }>
        <p>xxxxxxx</p>
    </HelloMessage>;,
    document.getElementById('example')
);

组件内没有 vue 的 data,他用 state,一个意思

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};     // vue的data
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.setState({ date: new Date() }),   // 改变data
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>现在是 {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('example')
);

事件绑定

class LoggingButton extends React.Component {
  handleClick = e => {  // 不用剪头函数,访问不到this
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>  <!-- 与vue写法不同,react没有:@全是{} -->
        Click me
      </button>
    );
  }
}

条件渲染

没有 v-if,v-show,都是类 js 语法控制

class LoggingButton extends React.Component {
    let button = null;
    if (this.state.isLoggedIn) {
      button = <a onClick={this.handleLogoutClick} />;
    } else {
      button = <a onClick={this.handleLoginClick} />;
    }
  render() {
    return (
      <div>
        <h1>
          // 方法1
          {this.state.isLoggedIn && <span>你好{this.state.uname}</span>}
          // 方法2
          {this.state.isLoggedIn ? '退出登录' : '登录'}
        </h1>
        {button}  // 方法3
      </div>
    );
  }
}

列表绑定,使用 map

  render(props, data) {
    return (
        <ul class="ul">
          {data.list.map((item, index) =>
            <item-movie data={item} key={index}></item-movie>
          )}
        </ul>
    )
  }

表单

没有 v-model,需要自己监听 change 事件

class 与 style

不可绑定对象

<!-- class要用className不可用对象,仅支持字符串 -->
<div className={index===this.state.currentIndex?"active":null}>此标签是否选中</div>
<!-- style可以用对象或字符串 -->
<h1 style={{color:'red',textAlign:'center'}}>Hello World!</h1>;

refs

this.refs => vue this.$refs

关于复用,没有 mixin,但引入高阶组件(HOC)的概念

即一个返回 React.Component 组件的函数,函数接受多个参数,在内部拼装出不同的组件。

but,都有 class 了为什么不用继承?

function withMixin(Comp, color) {
  // ...并返回另一个组件...
  return class extends React.Component {
    constructor() {
      super();
      this.state = { ... };
    }

    componentDidMount() {
      ... getData ...
    }

    render() {
      // ... 并使用新数据渲染被包装的组件!
      // 请注意,我们可能还会传递其他属性
      return <Comp data={this.state...} />;
    }
  };
}
const FinalComp = withMixin(trueComp, color);

关于它的一些原则:不要改变Comp;不要在 render 方法中使用 HOC;不要忘记Comp上的静态属性;

即js部分相同html不同的mixin,如果html相同js不同考虑使用组件将html封装?

命名规则 withXxxx

Hook

= React 16.8

根节点起始

ReactDOM.render(<h1>Hello, world!</h1>, document.getElementById("root"));
// 组件
import React, { useState } from "react";

function Clock() {
  // 声明一个新的叫做 “count” 的 state 变量
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>现在是 {this.props.date.toLocaleTimeString()}.</h2>
      <button onClick={() => setCount(count + 1)}>点击了 {count} 次</button>
    </div>
  );
}

差别对照表

import { useState, useEffect, useContext, useReducer } from "react";

Hook CLASS
useEffect(cb, []) componentDidMount\componentDidUpdate
useEffect(cb, []) => fn componentWillUnmount
useEffect(cb, [attrName]) (VUE)watch
[a, setA] = useState(value) state (无双向绑定,需要 this.setState({})来更新视图)
同 CLASS props
同 CLASS props(.children 为默认 slot,具名 slot 被当做一般属性传入)
同 CLASS refs
onClick={fn} onClick={this.fn} (fn 最好为剪头函数)
同 CLASS className={"active"} (仅字符串)
同 CLASS style={{color:'red'}}) (可对象)
import { useState, useEffect } from "react";

function App() {
  // 声明属性及其(更新视图的)变更方法
  const [num, setNum] = useState(1);

  useEffect(() => {
    console.log("hook mounted"); // mounted
    return () => console.log("hook beforeDestroy"); // beforeDestroy
  }, []); // 影响??

  return (
    <div className="App">
      <header className="App-header">
        <p onClick={() => setNum(num + 1)}>
          Edit <code>src/App.js</code> and save to reload.{num}
        </p>
        HOOK
      </header>
    </div>
  );
}

自定义 Hook

如果App的返回为一个值(非 jsx),则它是一个自定义 Hook(命名规则 usrXxxx)。

可以理解为一种没有模板的组件?

hook 的 useState 与 class 中的 state

  • 由于 react 不能直接修改 state,只支持整体覆盖原属性,所以在修改深层属性时需要拷贝对象 - 修改属性 - 覆盖原属性。

  • class 模式下所有调用都需要 this.xxx ,hook 可以直接使用 xxx

  • class 模式下方法需要使用剪头函数(或在构造函数中 bind(this)一下),hook 可以直接调用方法

VUE 与 REACT HOOK 差别对照表

VUE react Hook
beforeMount(created?) ??
mounted useEffect(cb, [])
beforeDestroy useEffect(cb, []) => fn
watch useEffect(cb, [attrName])
data [a, setA] = useState(value)
props props
slot props(.children 为默认 slot,具名 slot 被当做一般属性传入)
$refs refs
@click="fn" onClick={fn}
v-model 没有,自己实现
v-html dangerouslySetInnerHTML={{ __html: htmlstr }}
:class="{active: true}" className={"active"} (仅字符串)
:style="{color:'red'}" style={{color:'red'}}) (可对象)
mixin 高阶函数?
computed 自定义 Hook?
  • 命名规则:高阶函数使用 withXxxx

    使用方法类似继承

  • 命名规则:自定义 Hook useXxxx

    使用方法类似 vue 组件内由 $store.state 组成的计算属性

  • 全局变量 Vue.prototype.theme(组件内 this.theme)

<Provider theme={theme}><app/></Provider>(参见Provider及Context用法)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容

  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,448评论 1 33
  • 原教程内容详见精益 React 学习指南,这只是我在学习过程中的一些阅读笔记,个人觉得该教程讲解深入浅出,比目前大...
    leonaxiong阅读 2,835评论 1 18
  • 40、React 什么是React?React 是一个用于构建用户界面的框架(采用的是MVC模式):集中处理VIE...
    萌妹撒阅读 1,016评论 0 1
  • 从感性的角度讲,我是不屑于用VUE,觉得react套件用起来更顺手,但是vue现在越来火,所以也不得入vue(杂烩...
    zhoulujun阅读 1,451评论 0 1
  • 学习目的 熟练使用 React,并能运用 React 做一个项目,了解 React 开发。 学习技巧,用学...
    _1633_阅读 521评论 0 1