Introduction to the

React. Js is not a framework, it’s just a library. It only provides solutions at the UI (View) level. In the actual project, it can not solve all our problems, we need to combine other libraries, such as Redux, React-Router, etc., to help provide a complete solution.

render () {
  return (
    <div>
      <h1>React {(function () {return 'is good'})()}</h1>
    </div>)}Copy the code

Note that we use class directly to append the react. js element with a class name like

This method is illegal. Because class is a JavaScript keyword, a new way is defined in React. Js: className to help us add class names to elements.

Another special case is the for attribute, such as Male. Since for is also a JavaScript keyword, htmlFor is used in JSX instead of Male. Other HTML attributes such as style and data-* can be added just like normal HTML attributes.

render () {
  const isGoodWord = true
  return (
    <div>
      <h1>React small book {isGoodWord?<strong> is good</strong>
          : <span> is not good</span>
        }
      </h1>
    </div>)}Copy the code

If you return null inside an expression insert, then react.js will display nothing, essentially ignoring the expression insert.

renderGoodWord (goodWord, badWord) {
  const isGoodWord = true
  return isGoodWord ? goodWord : badWord
}

render () {
  return (
    <div>
      <h1>The React very {this. RenderGoodWord (<strong> is good</strong>.<span> is not good</span>
        )}
      </h1>
    </div>)}Copy the code

Combination of components

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Title extends Component {
  render () {
    return (
      <h1>The React little book</h1>)}}class Header extends Component {
  render () {
    return (
    <div>
      <Title />
      <h2>This is Header</h2>
    </div>)}}class Main extends Component {
  render () {
    return (
    <div>
      <h2>This is main content</h2>
    </div>)}}class Footer extends Component {
  render () {
    return (
    <div>
      <h2>This is footer</h2>
    </div>)}}class Index extends Component {
  render () {
    return (
      <div>
        <Header />
        <Main />
        <Footer />
      </div>
    )
  }
}

ReactDOM.render(
  <Index />.document.getElementById('root'))Copy the code

Component labels start with a capital letter

Event firing example

class Title extends Component {
  handleClickOnTitle () {
    console.log('Click on title.')
  }

  render () {
    return (
      <h1 onClick={this.handleClickOnTitle}>The React little book</h1>)}}Copy the code

These on* event listeners can only be used on normal HTML tags, not component tags. In other words,

This doesn’t work; these on* event listeners can only be used on normal HTML tags, not component tags.

An event triggers an invocation within a method

Pass in an Event object

The Event object represents the state of the Event, such as the element in which the Event occurred, the state of the keyboard key, the position of the mouse, and the state of the mouse button.

Events are usually used in conjunction with functions, which are not executed before the event occurs!

class Title extends Component {
  handleClickOnTitle (e) {
    console.log(e.target.innerHTML)
  }

  render () {
    return (
      <h1 onClick={this.handleClickOnTitle}>The React little book</h1>)}}Copy the code

This does not return the current instance in the event method. Instead, use:

class Title extends Component {
  handleClickOnTitle (e) {
    console.log(this)
  }

  render () {
    return (
      <h1 onClick={this.handleClickOnTitle.bind(this)}>The React little book</h1>)}}Copy the code

This bind mode is common in the React. Js event listener. Bind not only binds this to the current component instance; It also helps us pass the list element to the event listener when we render it.

The bind() method creates a new function, and when bind() is called, this of the new function is specified as the first argument to bind(), and the remaining arguments will be used as arguments to the new function.

class Title extends Component {
  handleClickOnTitle (word, e) {
    console.log(this, word)
  }

  render () {
    return (
      <h1 onClick={this.handleClickOnTitle.bind(this, 'Hello')} >The React little book</h1>)}}Copy the code

Pass parameters to the event handler

<button onClick={(e) = > this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)} >Delete Row</button>
Copy the code

The arrow Function and function.prototype. bind are implemented respectively.

Update status information about setState()

The setState method is provided by the parent Component class. When we call this function, react. js updates the component’s state and re-invokes the Render method, which then renders the latest content to the page.


  constructor (props) {
    super(props)
    this.state = {
      name: 'Tomy'.isLiked: false
    }
  }

  handleClickOnLikeButton () {
    this.setState({
      isLiked:!this.state.isLiked
    })
  }
Copy the code

When you call setState, React. Js does not immediately change state. Instead, you put the object in an update queue, and the new state will be extracted from the queue and merged into state later, and you can’t do that if you want to use the new state after setState

React.js passes the result of the previous setState to this function. You can then use the result to perform operations, operations, and return an object to update the state:

handleClickOnLikeButton () {
    this.setState((prevState) = > {
      return { count: 0}})this.setState((prevState) = > {
      return { count: prevState.count + 1 } // The previous setState returns count 0, and the current setState returns 1
    })
    this.setState((prevState) = > {
      return { count: prevState.count + 2 } // The last setState returned count 1, and the current setState returns 3
    })
    // The final result is this.state.count is 3
  }
Copy the code

We did setState three times above, but actually the component will only be rerendered once, not three times;

configurability

Configure this using props

class LikeButton extends Component {
  constructor () {
    super(a)this.state = { isLiked: false }
  }

  handleClickOnLikeButton () {
    this.setState({
      isLiked:!this.state.isLiked
    })
  }

  render () {
    const likedText = this.props.likedText || 'cancel'
    const unlikedText = this.props.unlikedText || 'thumb up'
    return (
      <button onClick={this.handleClickOnLikeButton.bind(this)}>{this.state.isLiked ? 👍 likedText: unlikedText}</button>)}}Copy the code

Set the property

class Index extends Component {
  render () {
    return (
      <div>
        <LikeButton likedText='has great' unlikedText='good' />
      </div>)}}Copy the code
   <LikeButton wordings={{likedText: 'has great'.unlikedText: 'good'}} / >Copy the code

The incoming method

class Index extends Component {
  render () {
    return (
      <div>
        <LikeButton
          wordings={{likedText:'has been praised,unlikedText:'good'}}onClick={()= >console.log('Click on like button! ')} / ></div>)}}Copy the code

A method is called

handleClickOnLikeButton () {
    this.setState({
      isLiked:!this.state.isLiked
    })
    if (this.props.onClick) {
      this.props.onClick()
    }
  }
Copy the code

The default parameters

class LikeButton extends Component {
  static defaultProps = {
    likedText: 'cancel'.unlikedText: 'thumb up'
  }

  constructor () {
    super(a)this.state = { isLiked: false }
  }

  handleClickOnLikeButton () {
    this.setState({
      isLiked:!this.state.isLiked
    })
  }

  render () {
    return (
      <button onClick={this.handleClickOnLikeButton.bind(this)}>{this.state.isLiked ? This. Props. LikedText: this. Props. 👍 unlikedText}</button>)}}Copy the code

If it is not passed in, the default properties in defaultProps are used.

Props cannot be changed once it is passed in

You cannot change the props passed in when a component is rendered. React.js expects a component to be able to output a certain UI appearance when it inputs certain props. If the props rendering process can be modified, this will result in the component’s appearance and behavior becoming unpredictable, which can lead to confusion for component users.

Component users can actively re-render new props into the component so that the presentation of the component determined by the props changes accordingly.

Methods that are not allowed to be modified

handleClickOnLikeButton () {
    this.props.likedText = 'cancel'
  }
Copy the code

Methods that allow modification

handleClickOnChange () {
    this.setState({
      likedText: 'cancel'.unlikedText: 'thumb up'})}Copy the code

Since setState causes Index to be re-rendered, the LikedButton receives the new props and re-renders, so its display morphology is updated. This is to modify the LikedButton appearance by passing in new props via re-rendering.

State is for the component to control its own state, while props is for the external to configure the component itself.

The list of rendering

const users = [
  { username: 'Jerry'.age: 21.gender: 'male' },
  { username: 'Tomy'.age: 22.gender: 'male' },
  { username: 'Lily'.age: 19.gender: 'female' },
  { username: 'Lucy'.age: 20.gender: 'female'}]class Index extends Component {
  render () {
    const usersElements = [] // Save the array of JSX rendered by each user
    for (let user of users) {
      usersElements.push( // Loop through each user, build JSX, push into array
        <div>
          <div>Name: {user. The username}</div>
          <div>Age: {user. Age}</div>
          <div>Gender: {user. Gender}</div>
          <hr />
        </div>)}return (
      <div>{usersElements}</div>
    )
  }
}

ReactDOM.render(
  <Index />.document.getElementById('root'))Copy the code

Simplify the writing

class Index extends Component {
  render () {
    return (
      <div>
        {users.map((user) => {
          return (
            <div>
              <div>Name: {user. The username}</div>
              <div>Age: {user. Age}</div>
              <div>Gender: {user. Gender}</div>
              <hr />
            </div>)})}</div>)}}Copy the code

For elements listed on the page as an expression nesting array, each element is assigned a key attribute, which must be a unique identifier for each element.

Key helps React identify which elements have changed, such as being added or removed. So you should give each element in the array a definite identity. An element’s key should ideally be a unique string that the element has in the list. In general, we use the id of the data as the key of the element. If the element has no specified ID, you can use the index of the element as the key

const todoItems = todos.map((todo, index) = >
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);
Copy the code

Elements in the map() method require a key attribute.

The constructor

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
 }
Copy the code

Lifecycle approach

The componentDidMount() method runs after the component has been rendered into the DOM

Once the Clock component is removed from the DOM, React calls the componentWillUnmount() lifecycle method

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date(a)}; }componentDidMount() {
    this.timerID = setInterval(
      () = > this.tick(),
      1000
    );
  }

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

  tick() {
    this.setState({
      date: new Date()}); }render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />.document.getElementById('root'));Copy the code

Scope components according to the single function principle. That is, a component can in principle only be responsible for one function. If it needs more functionality, consider breaking it up into smaller components.

Reference article:

React.docschina.org/docs/hello-…

Huziketang. Mangojuice. Top/books/react…