introduce

Recently, I took over an open source project on React. I read some basic tutorials on React before I got started. I had six months of front-end experience with Angular and two years of Vue, but I was still afraid of React.

React is almost the same as Vue. The only cost to learn is syntax (if you can understand the concepts of front-end frameworks and componentization).

But inside the three frames, the only official document that makes people feel praised and suitable for getting started, I personally think, personal! It’s Vue, so I’m going to use the document structure of Vue to explain the syntax and functions of Vue to you. Let’s re-read the Vue document and learn React.

  1. The structure of the whole article adopts the document catalog of Vue, some of which I have not used, and some of the corresponding descriptions may be removed because I am not clear in thinking
  2. For each section, the function implementation or syntax is transferred from the Vue document first, and then the corresponding React implementation or syntax is manually copied.
  3. The entire article is just over 10,000 words, and it is recommended that you read each example carefully. You may need 20 minutes?

Before you start reading, mentally say it out loud:

Vue. Js is what

This section will not introduce the two frameworks separately, as this article represents a must to be familiar with the basic syntax and philosophy of Vue, otherwise it is recommended to delete the article. In addition, it is recommended that you do not become a React expert, because the following content is as basic as the official document of Vue.

start

Vue starts with vue-CLI creating a project. This is not the case with vue-CLI. React is the same.

First you need to install create-react-app, which is your vue-cli:

npm install -g create-react-app
Copy the code

We then use it to build a React project:

create-react-app react-demo
Copy the code

Unlike vuE-CLI, which gives you a selection of configuration items, creat React is loaded until the end, and you can see a new React project infrastructure:

Declarative rendering

At the heart of vue.js is a system that allows you to declaratively render data into the DOM using a concise template syntax using V-bind and double curly braces:

<div id="app">
  <span v-bind:title="message">
    {{ name }}
  </span>
</div>
Copy the code
var app = new Vue({
  el: '#app'.data: {
    name: 'Hello Vue! '
    message: 'Page loaded on' + new Date().toLocaleString()
  }
})
Copy the code

React uses almost the same bidirectional binding method:

import React, {Component} from 'react' class DemoComponent extends Component {constructor() {super() // Treat this.state as data in your vUE this.state = { name: 'hello', title: + new Date().tolocaleString ()}} render() {return (// single curly braces for bidirectionality <span title={this.state.title}>{this.state.name}</span> ) } } export default DemoComponentCopy the code

I don’t want to add a tip to the picture.

  1. React two-way binding is usedSingle brackets
  2. React’s bidirectional binding properties also use single parentheses directly,No colons, no quotes
  3. React two-way binding variables are usedThis. The state. The variable name, instead of referring to the variable name directly

Conditions and cycles

In VUE, v-if and V-show are used to judge conditions, and V-for is used repeatedly

<div id="app">
  <p v-if="seen">Now you see me</p>
  <ol>
    <li v-for="todo in todos">
      {{ todo.text }}
    </li>
  </ol>
</div>
Copy the code
var app = new Vue({
  el: '#app'.data: {
    seen: true.todos: [{text: 'learning JavaScript' },
      { text: 'learning Vue' },
      { text: 'The whole cattle Project'}]}})Copy the code

React might cause a bit of trouble:

import React, { Component } from 'react'

class DemoComponent extends Component {
    constructor() {
        super(a)this.state = {
            seen: true.todos: [{text: 'learning JavaScript' },
                { text: 'learning Vue' },
                { text: 'The whole cattle Project' }
            ]
        }
    }
    render() {
        return (
            <div>/* Use the ternary expression */ {this.state.seen?<p>Now you see me</p>: null} /* Another use of ternary expressions */<p>{this.state.seen ? 'Now you see me' : null}</p>/* Dom traversal using map() */<ol>
                    {this.state.todos.map((item) => {
                        return (
                            <li>{item.text}</li>)})}</ol>
            </div>)}}export default DemoComponent
Copy the code
  1. React conditional judgment uses the js conditional expression feature.
  2. React loops are commonly usedmapMethod to iterate over the DOM structure that return needs to loop through
  3. Of course, this is just the basic usage

Processing user input

Vue adds an event listener with the V-ON directive, which calls the methods defined in the VUE instance: Vue also provides the V-model directive, which makes it easy to implement bidirectional binding between form input and application state:

<div id="app">
  <input v-model="message">
  <button v-on:click="reverseMessage">Inversion of the message</button>
</div>
Copy the code
var app = new Vue({
  el: '#app'.data: {
    message: 'Hello Vue.js! '
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split(' ').reverse().join(' ')}}})Copy the code

Then let’s look at how events and form elements are bound in React:

import React, { Component } from 'react'

class DemoComponent extends Component {
    constructor() {
        super(a)this.state = {
            message: 'Hello Vue.js! '
        }
    }
    reverseMessage(event) {
        this.setState({
            message: this.state.message.split(' ').reverse().join(' ')
        })
    }
    render() {
        return (
            <div>/* Single curly braces bind */<input value={this.state.message} />
                <button onClick={this.reverseMessage.bind(this)}>Inversion of the message</button>
            </div>
        )
    }
}
export default DemoComponent
Copy the code

Here comes the point:

  1. React uses the render function, so almost all features of React are implemented using JS syntax instead of command syntax
  2. Events such as click and tag attributes such as title and palceHolder use curly braces directly
  3. In React, bidirectionally bound variables do not respond to a series of js changes to variables. Any bidirectionally bound variables need to be updated in a page renderingEnclosing setState ({})Syntax, key is the variable name in state, value is the updated variable value (should be easy to understand if you’ve written a native applet)
  4. Methods can be defined directly in Class, as opposed to the methods object in vue, and usually you pass this to the method when you bind it, otherwise you’ll pass this to your methodthis.This scope error will be reported.

Vue instance

Create a Vue instance

Each Vue application starts by creating a new Vue instance with the Vue function:

Vue instances:

var vm = new Vue({
  / / options
})
Copy the code

The react instances:

import React, { Component } from 'react'

class DemoComponent extends Component {
  / / content
  render () {
  }
}
export default DemoComponent
Copy the code

Knowledge:

  1. A react Component is instantiated with a Class that inherits Component from React
  2. A React component must passrender ()returnJSXAnd only one can be returnedJSXElements (2Necessary conditions)
  3. What vue and React have in common is that the outermost layer must have oneA singletheThe root elementThe label

Getting easier, isn’t it? Next =>

Data and Methods

  • Vue data uses oneThe data functionReturns an object to hold variables in the current VUE instance, where the self-write methods are placedmethodsIn the
  • React data is placed instateIf you know enough about ES6 classes, you can easily understand what I’m talking about. (Watch ES6 again if you feel uncomfortable.)
  • There is another way to use internal variables:
render() {
		// Define variables directly in the render() function; after all, it is a function, which makes sense
        let tip = "Hello!"
        return (
            <div>
                {{tip}}
            </div>)}Copy the code

Since Render is a function, you can define variables inside the function directly before returning some DOM structure. React uses the render function, so almost all features of React are implemented using JAVASCRIPT syntax.

Instance lifecycle hooks

Rephrase it so I can type less:

Lifecycle hook vue react
Before instance creation beforeCreate – – –
After instance creation created constructor()
DOM before mount beforeMount componentWillMount
After DOM mount mounted componentDidMount
When data is updated beforeUpdate componentWillUpdate
After data update updated componentDidUpdate
Keep alive – when activated activated
When the keep-alive component is disabled deactivated
Before instance destruction beforeDestroy componentWillUnmount
After instance destruction destroyed componentWillUnmount
When an error occurs in a child component errorCaptured
  • , of course, there are still many specific subtle gap, there are some life cycle componentWillReceiveProps, componentWillReceiveProps, etc., but the life cycle in the table corresponding to the vue you are familiar with, It should be enough to give you a straightforward idea of what react’s life cycle is and what it does.

Template syntax

The interpolation

The text

The most common form of VUE data binding is text interpolation using “Mustache” syntax (double curly braces) :

<span>Message: {{ msg }}</span>
Copy the code

React uses curly braces directly, as already mentioned:

<span>Message: { this.state.msg }</span>
Copy the code

(Also do not know whether there is a corresponding V-once implementation, welcome to the comment science)

Raw HTML

Vue uses V-HTML to output real HTML directly, assuming we have an HTML string template called rawHtml:

<p> 
  <span v-html="rawHtml"></span>
</p>
Copy the code

React is simple because it is the render function, so it can:

render () {
  const rawHtml= `<span> is span </span>`
  return (
    <div>
      <p>{rawHtml}</p>
    </div>)}Copy the code

features

4. Vue uses V-bind to apply to HTML features:

<button v-bind:disabled="isButtonDisabled">Button</button>
Copy the code

React directly uses {} bindings:

<button disabled={this.state.isButtonDisabled}>Button</button>
Copy the code

Using JavaScript expressions

The basic expressions used in the official vUE example are:

{{ number + 1 }}

{{ ok ? 'YES' : 'NO' }}

{{ message.split('').reverse().join('') }}

<div v-bind:id="'list-' + id"></div>
Copy the code

Use simple operators, ternary expressions, and chained calls, while react is exactly how you would use js in your everyday life. All three work. In vUE, you can use {{}} directly to bind a method name or a method name in a calculated property, for example:

<div>{{changeName()}}</div>
Copy the code

React can also be written as an immediate function expression that returns:

<div>{(function () { return 'is div'})()}</div>
Copy the code

Calculate attribute

The react getter does not use the cache

The listener

React does not listen for changes in the react state. This is not done by me.

Class is bound to Style

Binding HTML Class

Vue can pass v-bind:class an object to dynamically switch classes:

<div
  class="static"
  v-bind:class="{ active: isActive, 'text-danger': hasError }"

></div>
Copy the code

The presence of active and ‘text-danger’ classes is determined by the data attributes isActive and hasError

Vue can also pass an array to V-bind :class to apply a class list:

<div v-bind:class="[activeClass, errorClass]"></div>
Copy the code
data: {
  activeClass: 'active'.errorClass: 'text-danger'
}
Copy the code

And in React,

  • In the first place!Class cannot be usedReact is used because class is the keywordclassNameInstead,
  • React class can only be converted to a string like this:
<div className={["activeClass",hasError? item.color :"'].join(' ')} ></div>
Copy the code
  • Or, es6 template string:
<div className={`activeClassThe ${hasError?item.color:"'} `} ></div>
Copy the code

Bind inline styles

Vue’s V-bind: Style object syntax is straightforward — it looks a lot like CSS, but is actually a JavaScript object. CSS attribute names can be camelCase or kebab-case delimited (remember to use quotes) :

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
Copy the code
data: {
  activeColor: 'red'.fontSize: 30
}
Copy the code

Of course, you can also define all styles as an object variable and bind to that object directly.

At this point, watch the knowledge,

{}

<div style={{display: this.state.isShow ? "block" : "none}} "></div>
Copy the code

For multiple styles, note the object form comma, to separate!

<div style={{display: this.state.isShow ? "block" : "none", color:"pink"}}></div>
Copy the code

I suggest you look at this and pause for a moment to tell the difference.

Conditions apply colours to a drawing

v-if

Vue is v-if, V-else, v-show and I won’t go into that, but this is a little bit easier:

<div v-if="Math. The random () > 0.5">
  Now you see me
</div>
<div v-else>
  Now you don't
</div>
Copy the code

React: JSX = JSX; react: JSX = JSX; react: JSX = JSX;

render () {
  const display = true
  const showDiv = <p>According to</p>
  const noneDiv = <p>hidden</p>
  return (
    <div>{display ? showDiv : noneDiv }</div>)}Copy the code

There is no vUE syntax like V-show, which saves on DOM switching performance.

The list of rendering

In VUE we can use the V-for directive to render a list based on an array.

<ul id="example-1">
  <li v-for="item in items">
    {{ item.message }}
  </li>
</ul>
Copy the code

As for the details of why to add a key, how to traverse the object, and how to v-for array detection problems will not go into the details.

The react loop was also mentioned at the beginning, using the map() method.

Form input binding

Form elements in Vue are bound using v-model bindings. Take input for example:

<input v-model="message" placeholder="edit me">
Copy the code

React also uses the element’s attribute value to bind directly

<input value={this.state.message} placeholder="edit me">
Copy the code

Component based

Basic example

As mentioned, an instance is basically a component and vUE has pure functional components later on, both framework components have the same concept.

Component reuse

Vue and React reuse components in the same way: reference components first and then use component name tags.

Vue references generally use the -interval tag, for example:

<div id="components-demo">
  <button-counter></button-counter>
</div>
Copy the code
import DuttonCounter from './modules/DuttonCounter'

export default {
  components: {
      DuttonCounter
  },
}
Copy the code

React reference tags use the export class name directly, and components must start with a capital letter:

import DuttonCounter from './modules/DuttonCounter'

function App() {
  return (
    <div className="App">
      <DuttonCounter />
    </div>
  );
}
Copy the code

Pass data to child components through Prop

Come, knowledge point, want to test of!

The parent component:

<super-man work="Superman"></super-man>
Copy the code

Child components receive:

<div>{{work}}</div>
Copy the code
export default {
  props: {
      work: {
        required: true.type: String}}},Copy the code

Then, look at the React props with an example:

class Index extends Component {
  render () {
    return (
      <div>
        <SuperMan work="Superman" />
      </div>)}}Copy the code

This is how a component passes values, much the same as vUE. Take a look at receiving component passes:

class SuperMan extends Component {
  constructor () {
    super(a)this.state = {}
  }

  render () {
    return (
      <div>{this.props.work}</div>)}}Copy the code

React also uses the props keyword to receive values from the parent component. The difference is that:

  1. All vue passes need to be placed in the props object of the child component before they can be used by the current child component, as if it were accessing variables of dataThis. The variableUse. The react is to useThis. Props. A variableThis way you can directly use all the variables passed by the parent component.
  2. React passes object parameters to child components{{}}Double parentheses pass objects directly
class Index extends Component {
  render () {
    return (
      <div>
        <SuperMan work={{name:'superman',task:'Save the World '}}
      </div>)}}Copy the code

3. Even transfer functions:

class Index extends Component {
  render () {
    return (
      <div>
        <SuperMan onClick={this.handleClick.bind(this)}/>
      </div>)}}Copy the code

And then, to add some extra information,

The treasure you didn’t pick up in the VUE file

If the parent component doesn’t pass any values, we might need a default value. In this case, you might want to use a ternary expression to check whether the parent component passes any values. React requires only:

class SuperMan extends Component {
  / / knowledge
  static defaultProps = {
    work: 'Superman by default'
  }
  constructor () {
    super(a)this.state = {}
  }

  render () {
    return (
      <div>{this.props.work}</div>)}}Copy the code

React defines defaultProps as the default configuration for the properties of props. This way we don’t need to check whether the config properties are passed in: if not, we can just use the default properties in defaultProps.

The PropTypes check for React props has been deprecated since React v15.5. Prop-types need to be installed separately. In React, we use prop-types to check components’ prop types.

npm install --save prop-types
Copy the code

It’s also easy to use, as you’ll see with an example:

/ / knowledge
import PropTypes from 'prop-types'

class SuperMan extends Component {
  / / knowledge
  static propTypes = {
    work: PropTypes.string
  }
  
  constructor () {
    super(a)this.state = {}
  }

  render () {
    return (
      <div>{this.props.work}</div>)}}Copy the code

Simple, by introducing prop-types and adding a class attribute called propTypes that specifies the data type for the variables passed in by your props, this is equivalent to type:String for the vue.

Then, let’s look at how required: true is implemented in React:

import PropTypes from 'prop-types'

class SuperMan extends Component {
  static propTypes = {
    work: PropTypes.string.isRequired  / / knowledge
  }
  
  constructor () {
    super(a)this.state = {}
  }

  render () {
    return (
      <div>{this.props.work}</div>)}}Copy the code

A closer look at the difference from the previous example is that when we specify proptypes.string, we follow it with the isRequired keyword to enforce that a component parameter must be passed in.

Finally, how do react implement component parameter verification? I haven’t used this yet, but I looked it up for you, and it’s pretty much what I guessed. I just use the function:

import PropTypes from 'prop-types'

class SuperMan extends Component {
  static propTypes = {
    work: function(props,propName,componentName){}/ / knowledge
  }
  
  constructor () {
    super(a)this.state = {}
  }

  render () {
    return (
      <div>{this.props.work}</div>)}}Copy the code

Use a custom function, the default spread and props, respectively, propName, the componentName, calibration Error is then return the new Error (‘ Error message ‘); That’s it.

Here are some other examples I’ve seen, which I haven’t used yet, but which are good tips:

// Specify enumeration types: you can restrict attributes to specific values
optionalEnum: PropTypes.oneOf(['News'.'Photos']),

// Specify multiple types: You can also restrict attribute types to certain specified types
optionalUnion: PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number,
  PropTypes.instanceOf(Message)
]),

// Specify an array of some type
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

// Specify that the type is an object and the object attribute value is a specific type
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
Copy the code

Listen for child component events

React and Vue share the same component characteristics — one-way data flow. In React, if you want to change the value of the parent component, you need to use a method to trigger the parent component’s method. The parent component’s own method operates on the value of the parent component.

The react method is used to emit $emit from the parent component. The react method is used to emit $emit from the parent component. The react method is used to emit $emit from the parent component.

/ / the parent component
class Index extends Component {
  this.state = {type:'Little Superman'}
  
  changeType(data) {
    this.setState({
      type: data // Replace type in the parent component with the value passed by the child component
    })  
  }
  
  render () {
    return (
      <div>
        <SuperMan work="Superman" super={this.fn.changeType(this)}/>/ / knowledge</div>)}}Copy the code
/ / child component
class SuperMan extends Component {
  constructor () {
    super(a)this.state = {childText:Superman.}
  }
  
  clickFun(text) {
    this.props.super(text)// This is where the value is passed to the props event
  }
  
  render () {
    return (
      <div onClick={this.clickFun.bind(this, this.state.childText)} >
        {this.props.work}
      </div>)}}Copy the code

Instead of using $emit, you can call the parent component’s methods via this.props.

Distribute content through slots

First of all, how do we use a slot in vUE:

/ / the parent component<my-component>
  <p>superman</p>
</my-component>/ / child component<div class="child-page">
  <h1>Infinite Earth Crisis</h1>
  <slot></slot>
</div>// Render the result<div class="child-page">
  <h1>Infinite Earth Crisis</h1>
  <p>superman</p>
</div>
Copy the code

React implements slots like vue:

/ / the parent component
ReactDOM.render(
  <MyComponent>
	<p>superman</p>
  </MyComponent>.document.getElementById('root'))class MyComponent extends Component {
  render () {
    return (
      <div class="child-page">
        <h1>Infinite Earth Crisis</h1>
        {this.props.children}
      </div>)}}Copy the code

{this.props. Children} renders the JSX content to the specified structure of the page.

The end of the

By the time I finished writing, it had been a week on and off. I looked at 11386 words in the lower right corner, and the code research on the project was similar. Because it was an open source project, a large number of higher-order components were composed of some pure function components.

So far, the syntax and functions of react have been sorted out according to the structure in the VUE document (some of them have been deleted). If you can compare each example carefully, I think you can understand a React project even if you can’t write react.

Add a point of knowledge if there are supplementary comments, and give a thumbs-up if there are no supplementary comments.

thank you