Reaction Chat: Analysis and Sharing of the Basic Textbook of Reaction Official Website

Posted by etnastyles on Mon, 01 Jul 2019 04:06:45 +0200

Basic Analysis of Reaction Official Web Course

First issue: Basic Analysis of Github Reaction Official Course

Open Reaction English official website, are you still because your English is not good, using translation software to see confusion. Don't worry, I combined the latest react official website tutorial, after a detailed study, based on my own experience, summed up the knowledge of the basic chapter, as well as the follow-up summary of the advanced chapter.

1. What's the difference between react writing using Redux and without redux?

Answer: Components are written in the same way, but state is not necessarily handed over to the internal management of components. It may be put on the store for unified management.

2. Know react, a hello world!

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

3. How to use react?

Answer: It is recommended that you use ES6 grammar to write react. First, you need Babel to compile your ES6 code. Second, you can use ES6 grammar such as => (arrow function), class (class), template text, let and const statements.

4. Introduction to JSX

Answer: JSX is an expression that has a root tag that can be embedded internally and wrapped in {} (braces). It looks like it's part of html, or an HTML module.

class T extends React.Component {
    render() {
        return <div className="left-enter" style={}>{value}</div>
    }
}

From the above code example, you can see several differences from html, class ="className, style is an object, you can also use {} to insert data in the dom element.

Using JSX can also prevent XSS (cross-site scripting attacks), because JSX is just an expression, it needs to be converted into a string before it can be rendered to the real DOM, but for real hackers, this is not safe either.

4. Concept of Elements and Components

react component:

class T extends React.Component {
    render() {
        return <div className="left-enter" style={}>{value}</div>
    }
}

The react element:

<div className="left-enter" style={}>{value}</div>

5. Use of Components

Function Components: Function Components have no state and lifecycle, but you can return a react element.

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

Class component: Very powerful, with its own state and lifecycle. Like function components, class components also need to return a react element.

class Welcome extends React.Component {
  componentWillMount() {}
  componentDidMount() {}
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

In a large and complex website application, how to split components? Official website says that the finer the component is split, the stronger the reusability. From the point of view of actual development, this statement is not wrong, but
It will bring a serious problem, that is, too many components are inconvenient to manage. When someone uses third-party react components, only those open source components with very strong documentation are available
Only in this way can you improve the efficiency of your development. Documentation is the most important step if your own components want to be broken down into detail.

react also mentions that the data passed to the component is "read-only" to ensure that the data in the component is "pure data" and that input is output. So, if you need to modify props.data in the component
What should we do?

render() {
    const { data } = this.props
    //Define a new variable to save the modified value.
    let _data = data + 1;
}

6. State and life cycle of components

We mentioned earlier that components are divided into function components and class components. Function components are stateless, class components are stateful and life cycle.

What is state?

Answer: Popular understanding is the different performance of components at different times. For example, a button component may have active state, non-clickable state, display state, hidden state, etc. In react, state is used to save these states.
The state itself not only represents the state of the component, but also stores the data of the component.

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        isShow: true,
        text: props.text,
        disabled: true
    };
  }

  render() {
      const { isShow, text, disabled} = this.state
      return <button disabled={disabled} style={{display: isShow ? "block" : "none"}}>{text}</button>
  }
}

If you want to modify the state, use it. Note that you can't modify the state directly in the render function. Instead, you need to trigger the state update through events.

this.setState({
    isShow: false,
    disabled: false
})

Because setState has batch processing capabilities, this method may not necessarily be updated synchronously. If you need to rely on the last state and the calculation of this state, you need to write the following form.

this.setState((prevState, props) => {    
      text: prevState.text++
    });

demo website: http://codepen.io/hyy1115/pen...

Sometimes, the child component does not need to pay attention to its own state, but changes through the state of the parent component. At this time, the child component can be written as a function, passing the state of the parent component through props.

react life cycle
The life cycle represents the lifetime of a component, from birth to glory to death. The three most important and commonly used states are:

Compoonent WillMount: Born, set the state and properties of components.

Compoonent DidMount: Rendered, I'm no longer JSX, but real DOM.

Compoonent Will Unmount: Dead. Handle the legacy before you die.

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        isShow: true,
        text: props.text,
        disabled: true
    };
  }
  
  componentWillMount() {
      //Born, you can give me data and set my status.
  }
  componentDidMount() {
      //How good to live
  }
  componentWillUnmount() {
      //I'm dying. Clean up all traces of my life.
  }

  render() {
      const { isShow, text, disabled} = this.state
      return <button disabled={disabled} style={{display: isShow ? "block" : "none"}}>{text}</button>
  }
}

There are several other life cycles, which are not very common. When you need to use them, look at other people's blogs.

7. Event handling

 <button onClick={(e) => this.handleClick(e)}>
 Button
</button>

<input type="text" onChange={(e) => this.handleClick(e)} />

8. Conditional Rendering

In the previous button example, we have used conditional rendering. Conditional rendering is judged by state. Commonly used are control style, className, DOM attributes, JSX.

Take a few common examples.

render() {
    return (
        <div>
        {
            this.state.isShow && <button>Button</button>    
        }
        </div>
    )
}
render() {
    return (
        <div>
        {
            this.state.isShow ? <button>Button</button> : <span>text</span>
        }
        </div>
    )
}
render() {
    return <button disabled={this.state.disabled}>Button</button>
}

9. List Rendering

Two points of attention:

The array is empty.

A key must be given.

render() {
    const { arr } = this.state
    return arr.length > 0 && arr.map((value, key) => <li key={key}>{value}</li> )
}

10. Forms

Once I had an interview with Ali, I got the knowledge of the react form.

Controlled components: Form components that are input controlled by react.

In the following example, the value of input is determined by state. The user input triggers the onChange event and then updates the state to modify the value.

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() {
    return (
          <input type="text" value={this.state.value} onChange={this.handleChange} />
    );
  }
}

Perhaps you don't see the difference between an authentic input element and a real DOM element. Value is maintained by inupt itself, and we don't bind value.

<input type="text">

textarea is the same as input.

Select is slightly different, binding value to select rather than option.

<select value={this.state.value} onChange={this.handleChange}>
    <option value="1">1</option>
    <option value="2">2</option>
</select>

Another is the case of multiple input boxes, such as login, account number, password, etc. At this time, the operation of these different input can be through ref or name, class, id and other methods to setState, see
Official demo.

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form>
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
      </form>
    );
  }
}

Uncontrolled components: Simply, components that DOM maintains its own state are not controlled by react. You can set defaultValue for it, but you can't set State.

<input type="text" ref={(input) => this.input = input} defaultValue="Default values"/>

It is believed that someone will try to set defaultValue and then execute setState to modify the value, so that the console will issue a warning.

Summary: Controlled components refer to react-controlled components. value and state in form components are synchronized. Uncontrolled components refer to components that are not react-controlled. Form components refer to components that are not react-controlled.
Value does not synchronize through state, it can only operate DOM to read value.

11. State Improvement

You must have heard of variable elevation and function elevation, so what is state elevation?

First of all, you need to understand two-way binding and one-way data flow. In two-way binding, data can be shared between different components. It does have great benefits, but in react,
It is not recommended to use two-way binding, but to use state elevation.

I remember talking to an interviewer in Arie who asked me to use react to achieve bi-directional binding, and I thought that react should be implemented by state upgrade. He was not persuaded in the end. Maybe let Dan come.
It's useful to talk to him, haha.

State Upgrading: State advocates one-way data streams, where data flows from parent components through props to child components. If you are in child components, you need to modify state to share data updates with other child components.
You need to use a callback function to update the data to the parent component, and then flow from the parent component to the other child components, in order to ensure that the data has a single source.

If data is arbitrarily shared between real and sub-components, later maintenance can be painful, especially when finding bug s.

Look at an example of state improvement.


class Child extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.upDateValue(e.target.value);
  }

  render() {
    const {name, value} = this.props;
    return (
      <div>
        <p>{name}: </p>
        <input value={value}
               onChange={this.handleChange} 
          />
      </div>
    );
  }
}

class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: '', name: ''};
    
    this.upDateValue = this.upDateValue.bind(this);
  }

  upDateValue(value) {
    this.setState({value: value})
  }
  
  render() {
    const {value} = this.state;

    return (
      <div>
        <Child name="Fig. 1" value={value} upDateValue={this.upDateValue} />
        <Child name="Component 2" value={value} upDateValue={this.upDateValue} />
      </div>
    );
  }
}

ReactDOM.render(
  <Demo />,
  document.getElementById('root')
);

demo website: http://codepen.io/hyy1115/pen...

12. Choose combination or inheritance?

Students who have used native js or jQuery may be familiar with the basics, and inheritance can extend many functions.

In react component development, each of our react components is inherited from React.Component.

class MyComponent extends React.Component {
    
}

We do not recommend that you inherit MyComponent.

//Not recommended
class NextComponent extends MyComponent {
    
}

You should take full advantage of the powerful performance of react components and develop all the components you need to inherit to React.Component. The nesting between components is very powerful, you can nest function components, nested class components.

Details go to: https://facebook.github.io/re...

Last

So far as react basic analysis is concerned, by learning these basic knowledge, you can already make a very rich application of react, of course, combining https://github.com/hyy1115/re... come
Learning can help you practice your product faster. A kind of

Topics: Javascript React github JQuery