Basic part of React

Keywords: Javascript Front-end React

The basic part of react also needs us to grasp it in depth.
Like other bloggers, I suggest using the JS package that is convenient for beginners to reference first. I'm also a beginner. That's what I did before. websotrm and vscode tools are OK. The three packages are react.js (Core Library), react-dom.js (providing DOM related services) and brower.js (converting jsx syntax into JS syntax)

1, React Basics

1,ReactDOM.render()

It is the most basic method of react, which is used to convert the template into html language and insert the specified DOM node

ReactDOM.render(
    <h1> Hello,world <h1>,
   document.getElementById('example')
);

Insert an h1 title into the example node above

2. Style settings

style
ReactDOM.render(
   <div style={{color:'red'}}>
     XXXX
   </div>,
   document.body
);
Class name( className)
ReactDOM.render(
   <div className="box">content</div>,
  document.body
);

If you use ant design, you can also install the styled components package to decorate the original components

3. Event binding

function say(){
      alert("How old are you?")
}
React.render(
     <button onClick={say}>
     document.body
);

Compared with the previous html, it adopts the form of "{function()}". In addition, when the event is bound, the event is written in a hump style.

4. Components

React allows you to encapsulate code into components, and then insert this component in a web page similar to inserting html tags. The React.createClass method is used to generate a component class

var Hello = React.createClass({
     render: function(){            // There is more than one way to write, just according to your preferences
          return  <h1>hello world</h1>;
     }                                             
});
ReactDOM.render(
     <Hello />,  
     // More interesting, the symbols here can not be omitted           
     document.getElementById('app')     
);

Compare the recommended method. Install the es syntax package prompt in vscode, and then press the rcc shortcut key.

4.1 component props

It is only passed as an attribute and is immutable;
The properties of this.props object correspond to the properties of the component one by one.

var Hello = React.createClass({
    render:function(){
         return <h1>Hello {this.props.name}</h1> 
    }
});
ReactDOM.render(
   <Hello name="veblen"/>
   document.getElementById('app') 
);

this.props.children attribute, which represents all child nodes of the component

var NodeList = React.createClass({
     render: function(){
            return (
                 <ol>
                 {
                      this.props.children.map( function(child){
                             return <li>{child}</li>
                      })
                 }
                 </ol>  
      ); 
    }
});
ReactDOM.render(
     <NodeList>
         <span>hello</span>
         <span>world</span>
     </NodeList>
     document.body
);

There are three possible values for this.props.children:
1. If the current component has no child nodes, it is undefined
2. If there is a child node, the data type is object
3. If there are multiple child nodes, the data type is array
React provides a tool method, React.Children, to handle this.props.children
React.Children.map to traverse the child nodes without worrying about the data types of the child nodes

React.Children.map(this.props.children,function(child){
     return  <li>{child}</li>
})
4.2 component PropTypes

Component properties can accept any value, including strings, objects, functions, etc;
Sometimes, we need a mechanism to verify whether the parameters provided by others meet the requirements when using components.
PropTypes property is used to verify whether the properties of component instances meet the requirements.

var MyTitle = React.createClass({
      propTypes:{
          title: React.PropTypes.string.isRequired,
      },
      render:function(){
          return <h1>{this.props.title}</h1>;
     }  
});

In this component, we create a title attribute. PropTypes tells React that this title attribute is required and its value must be a string.
The getDefaultProps method can be used to set the default value of component properties

ar MyTitle =React.createClass({
     getDefaultProps: function(){
          return {
               title: 'hello world'
          };
     },
     render: function(){
          return <h1>{this.props.title}</h1>;
     }
});
ReactDOM.render(
       <MyTitle />,
       document.body
);

Code output hello world

4.3 component internal events
var Mybtn=React.createClass ({
     say:function(){
             alert("How old are you!")
     }
     render:fucntion(){
           return (
                  <button onClick={this.say} />
           )
     }
})
// this points to the component instance

You may need to know something about this pointing event. After all, it's one-sided

4.4 component state

Components have to interact with users. A major innovation of React is to regard components as a state machine. One open four have an initial state, and then users interact, resulting in state changes, which triggers the re rendering of the UI

var LikeButton = React.createClass({
      getInitiaState:function(){    // Now the grammar has changed so much that it doesn't have to be written so much
                return {liked:true};
      },
      handleClick:function(event){
             this.setState(liked: !this.state.liked);
      },
      render:function(){
             var text = this.state.liked? 'love':'hate';
             return(
                  <p onClick={this.handleClick}>
                         I{text}veblen
                  </p>   
             );
      }
});
ReactDOM.render(
    <LikeButton / >,                                 
   document.getElementById('app')
);

Interpretation: for the LikeButton component, its getinitialstate method is used to define the initialization state, that is, an object that can be read through this.state property. When the user clicks the component and the state changes, this.setState method modifies the state value. After each modification, this.render method is automatically called to render the component again.
Both this.props and this.state are used to describe the characteristics of components, which may cause confusion. Distinguish methods:
this.props represents features that will not change once defined;
this.state is a feature that changes with user interaction.

4.5 bidirectional binding of component data
var Input = React.createClass({
     getInitialState:function(){
            return {value: 'Hello!'}; 
     },
     handleChange: function(event){
           this.setState({value:event.target.value}); 
    },
    render: function(){
         var value = this.state.value;
        return (
           <div>
                 <input type='text' value={value} onChange={this.handleChange} />
                 <p>{value}</p>
           </div>     
        ); 
    }
});

ReactDOM.render(<Input / >,document.body);

//This place needs to be added. After all, it is a good knowledge point

4.6 component life cycle

componentWillMount() - before mounting
componentDidMount() - after mounting
componentWillUpdate(object nextProps,object nextState) - before update
componentDidUpdate(object prevProps,object prevState) - after update
componentWillUnmount() -- before destruction

5. Operate real DOM

A component is not a real DOM node, but a data structure that exists in memory, called a virtual dom. It will become a real DOM only after it is inserted into a document. According to the design of react, all DOM changes first occur on the virtual DOM, and then reflect on the real DOM according to the actual changes. This algorithm is called dom diff, which can greatly improve the performance High performance of web pages. However, sometimes it is necessary to obtain real DOM nodes from components, and the ref attribute is used

var MyComponent = React.createClass({
    handleClick: function(){
        this.refs.myTextInput.focus();      
    },
    render:function(){
        return(
            <div>
                 <input type = "text" ref="myTextInput" />
                 <input type = "button" value= "focus the text input" onClick={handleClick}                 
            </div>  
        );
    }
});
ReactDOM.render(
       <MyComponent />,
       document.getElementById('app') 
);

In the above code, the child node of the component myComponent has a text input box to get the user's input. At this time, the real dom node must be obtained, and the virtual dom cannot get the user's input. In order to do this, the text input box must have a ref attribute, and then this.refs.[refName] will this real dom node.
It should be noted that since this.ref.[refName] property obtains the real DOM, it can only be used after the virtual DOM is inserted into the document, otherwise an error will be reported. In the above code, by specifying the callback function of Click event for the component, it is ensured that it can be read only after the Click event occurs in the real dom

In fact, the main content of this blog comes from a blogger in Jianshu. I just want to know and supplement this part. I typed it by hand according to his content and made a long impression. He also has a good introduction to jsx, redux and communication between components. You can also have a good look at node.js
Original link: https://www.jianshu.com/p/c509cec33594

On paper, you will eventually feel shallow, and you should practice it.
Later, I will practice these contents and other contents by myself. Come on!

Posted by jbingman on Fri, 29 Oct 2021 02:16:56 -0700