Reactjs Introduction (iv)--component API

Source: Internet
Author: User

This article will introduce the API of the React component, where the main API we have introduced in the first article, here can be a restudying.

The code in this article is also available on my GitHub.

SetState

Parameters: Nextstate (object), [Callback (function)]

Set a key (property) value for Nextstate (don't forget that we can get the value of Nextstate in the shouldcomponentupdate method to compare with the current this.state). /c5>, and then the next time the EventLoop is this.state the corresponding key will be updated to the set value.

Usually if we want to re-render the component in an event or a callback (triggering UI updates), SetState is the most common trigger method because we bind the UI content directly (or through certain conditions) to the state. Once the state has changed and touches the logic of the binding, the UI content will naturally follow the same changes:

    varComponent1 =React.createclass ({getinitialstate:function() {            return{isclick:!1}}, Componentdidupdate:function() {Console.log (' Componentdidupdate ')}, CLICKCB:function() {             This. SetState ({isclick:!0            }, function() {Console.log ( This. State.isclick)}) }, Render:function() {            return(<div onclick={ This.clickcb}>isclick:{ This. State.isclick? ' Yes ': ' Nope '}            </div>)        }    }); vardiv = document.getElementById (' A '); React.render (<component1/>, div);

As we determine what to display in the div by State.isclick, we change the state of the State.isclick when we click on the div, triggering the binding condition to change the contents of the Div.

Note that in this code we use the Componentdidupdate method, as described in the second article, which is triggered immediately after the component is re-rendered. After we click on the div, we find that the print order is this:

The callback that we defined in the SetState method is executed after the component is re-rendered, not immediately after we have changed the value of Nextstate.

Replacestate

Parameters: Nextstate (object), [Callback (function)]

Similar to SetState (), but none of the previously existing state keys (key) are removed, and the keys are not in nextstate.

How do you understand this sentence? Let's look at this example:

    varComponent1 =React.createclass ({getinitialstate:function() {            return{isclick:!1, ABC:1//Notice Here we initialize a state.abc.}}, CLICKCB:function() {             This. Replacestate ({isclick:!0            }, function() {Console.log ( This. State)}) }, Render:function() {            return(<div onclick={ This.clickcb}>isclick:{ This. State.isclick? ' Yes ': ' Nope '}            </div>)        }    }); vardiv = document.getElementById (' A '); React.render (<component1/>, div);

Note that we also define an additional ABC State property in Getinitialstate, but try to print the this.state after replacestate, and you will find that the STATE.ABC has been deleted (if replaced by setState will not be deleted).

So as the name implies, Replacestate is a complete replacement of the state of the method, the ordinary use should be careful to use, to avoid deleting some important State properties.

ForceUpdate

Parameters: [Callback (function)]

As the name implies, the rendering component is forced at any call, for example, even if Shouldcomponentupdate returns false:

    varComponent1 =React.createclass ({shouldcomponentupdate:function(Nextprops, nextstate) {Console.log ( This. State, Nextstate);  This. ForceUpdate (function() {Console.log (' Force render complete ')            }); //force rendering, removing this line will not render            return false; }, Componentdidupdate:function() {Console.log (' Componentdidupdate ')}, Getinitialstate:function() {            return{isclick:!1}}, CLICKCB:function() {             This. SetState ({isclick:! This. State.isclick}) }, Render:function() {            return(<div onclick={ This.clickcb}>isclick:{ This. State.isclick? ' Yes ': ' Nope '}            </div>)        }    }); vardiv = document.getElementById (' A '); varC1 =React.render (<component1/>, div);

Note that the callback for this method is also performed after re-rendering.

Another scenario that uses forceupdate can be that we do not use props or state as a condition for triggering rendering, such as using a variable as the UI content, which can be used when the value of the variable is changed and we want to trigger the rendering, which is not recommended, of course.

Getdomnode ()

Returns the DOM element that the component/reactelement mounts to on the page:

    varComponent1 =React.createclass ({getinitialstate:function() {            return{isclick:!1}}, CLICKCB:function() {             This. SetState ({isclick:!0            }, function() {Console.log ( This. State.isclick)}) }, Render:function() {            return(<div onclick={ This.clickcb}>isclick:{ This. State.isclick? ' Yes ': ' Nope '}            </div>)        }    }); vardiv = document.getElementById (' A '); varc =React.render (<component1/>, div    ); Console.log (C.getdomnode ())

Printing results:

Also, if Render returns null or FALSE, This.getdomnode () returns NULL.

Ismounted ()

Returns a Boolean value that ismounted () returns True if the component is mounted to the DOM.

It applies to the scenario of an asynchronous request:

    varComponent1 =React.createclass ({getinitialstate:function() {            return{content:' Hello '}}, Componentwillmount:function() {dosomething (props). Then (function(content) {if( This. ismounted ()) {                     This. SetState ({content:content}); }}.bind ( This)); }, Render:function() {            if( This. State.isclick) {                return(<div>content:{ This. state.content}</div>)}Else {                return false;    }        }    }); vardiv = document.getElementById (' A '); varc =React.render (<component1/>, div);

As the code above, we execute an asynchronous request dosomething at Componentwillmount, which modifies the value of state when it gets to the server data, provided that the component is mounted on the page.

If the asynchronous request completes quickly, we get to the new content when the component may still be in the mount (mounting) process, then state remains the same (because ismounted () returns false at this time).

SetProps

Parameters: Nextprops (object), [Callback (function)]

Similar to SetState, but modified by props:

    varComponent1 =React.createclass ({CLICKCB:function() {             This. SetProps ({name:' Cnblog '            }, function() {Console.log ( This. Props)}) }, Render:function() {            return(<div onclick={ This.clickcb}>                    { This. props.sayhi | | ' www. '}                    { This. props.name | | ' Nothing '}            </div>)        }    }); vardiv = document.getElementById (' A '); React.render (<component1 name= "Vajoy" sayhi= "Hello"/&GT;, div);

Replaceprops

Parameters: Nextprops (object), [Callback (function)]

Similar to SetProps, will replace the existing props key, we still use the last piece of code, but the SetProps replaced Replaceprops:

    varComponent1 =React.createclass ({CLICKCB:function() {             This. Replaceprops ({name:' Cnblog '            }, function() {Console.log ( This. Props)}) }, Render:function() {            return(<div onclick={ This.clickcb}>                    { This. props.sayhi | | ' www. '}                    { This. props.name | | ' Nothing '}            </div>)        }    }); vardiv = document.getElementById (' A '); React.render (<component1 name= "Vajoy" sayhi= "Hello"/&GT;, div);

When we click on the component, we will find that Props.sayhi has been removed:

Refs

In fact, this is not a component of the method, but also a common in the component of a small trick, so here to do the introduction.

As we mentioned earlier, you can use the Reactclass.getdomnode () method to get the DOM node that the component renders on the page, but what if we want to get to a DOM element in the component?

At this point we can use the form of defining refs to make it easier for us to get the corresponding elements:

    varComponent1 =React.createclass ({CLICKCB:function(e) {if(E.target = = = This. Refs.li2.getDOMNode ()) {Alert (' You ordered the second Li. ')}}, Render:function() {            return(<ul onclick={ This.clickcb}> <li>1</li> <li ref= "Li2" >2</li> <li& Gt;3</li> </ul>)        }    }); vardiv = document.getElementById (' A '); React.render (<component1/>, div);

As we bind a ref attribute to the second <li> in the component, the value is "Li2", which means that we can get to the reactelement in the component as This.refs.li2.

Then bind the point-click event, when clicked to determine whether the Li element is equal to This.refs.li2.getDOMNode (), if so, then pop alert.

The official also gave a practical demo:

  varAPP =React.createclass ({getinitialstate:function() {      return{userinput: '}; }, HandleChange:function(e) { This. SetState ({userinput:e.target.value}); }, Clearandfocusinput:function() {      //Clear the input       This. SetState ({userinput: '},function() {        //This code is executed immediately after the component is redrawn:         This. Refs.theInput.getDOMNode (). focus ();//Input successful focus (focus)      }); }, Render:function() {      return (        <div> <div onclick={ This.clearandfocusinput}>Click to Focus and Reset</div> <Input ref= "Theinput"//we can get it in the component with This.refs.theInput.value={ This. State.userinput} onChange={ This. HandleChange}/> </div>      ); }  });

At this point we are basically getting started with most of React's major APIs, and we will further learn React in the form of project practice.

Mutual Encouragement ~!

Reactjs Introduction (iv)--component API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.