React several ways to do tab switching

Source: Internet
Author: User

Recently engaged in a PC-side activity, engaged for one months, very annoying, because compared to the PC side, prefer a little more mobile. Because the mobile side can also engage my react.

Today, I'll summarize some of the options for tab switching in React, because tab switching is mostly used. Of course, you can also in react with jquery or zepto to achieve, but since all use react, can use JQ, as far as possible without JQ. But I had to spit it out, and in the simple things of jquery, a little bit more complicated in react.

At present, I use the tab switch only two ways, so temporarily summarize these two, later encountered other summary.

The first kind, only the sub-label in the change, the layout of the content does not change. Similar to the following

This type of switch only needs to click on the above label, send different requests, the following layout is the same.

The second is that both the tab and the content need to be switched, which is more common. As follows

Talk is cheap. Show me the code (think more interesting translation is: nonsense, put code over)

The first, just the Way tab tab is switched

Import React from ' React '; class Newslist extends React.component {constructor (props) {super (props);  This. State ={tabs:[{tabname:"Hot News", id:1}, {tabname:"Cooperation broadcast", Id:2}, {tabname:"Industry Consulting", Id:3}, {tabname:"Operation Strategy", Id:4}], Currentindex:1,        }; } componentdidmount () {} tabchoiced= (id) = ={        //How to Tab switch         This. SetState ({currentindex:id}); } render () {var_this= This; vartablist= This. State.tabs.map (function(res,index) {//traverse the tab, if the label's ID equals TabID, then the label adds one more active classname            vartabstyle=res.id== This. State.currentindex? ' Subctrl active ': ' Subctrl '; return<li Key={index} onclick={ This. Tabchoiced.bind (_this,res.id)} classname={tabstyle}>{res.tabname}</li>}.bind (_this)); return (            <div classname= "Listwrap" > <ul classname= "Subnavwrap" >{tabList}</ul> <div classname= "Newslist" >                    {/** The general news list here **/}                </div> </div>)}}exportdefaultNewslist;

First we initialize the array that has been given the tab tag and add an ID to each item inside the array, Then set a currendindex that currently shows the number of the first. Then the tag is traversed, if the tag ID equals Currendindex, then add an active classname, otherwise No. This allows the click Tag to display the highlighted status

Each time a new tag is clicked, the ID of the tag is passed over, so that currendindex equals the ID of the tag being clicked. For example, click on the ID 2 tag, so the next time the Currendindex is also equal to 2, so that the second in the highlight, so that the tab switch.

Second, the content is switched along with the tag

This is also more common. For the time being I have two ways of doing this.

Method 1: In front of just the label switch formally improved:

Import React from ' React '; class Newslist extends React.component {constructor (props) {super (props);  This. State ={tabs:[{tabname:"Social News", id:1}, {tabname:"The World of Sports", Id:2}, {tabname:"Entertainment Circle", Id:3},], Currentindex:1,        }; } componentdidmount () {} tabchoiced= (id) = ={        //tab switch to method         This. SetState ({currentindex:id}); } render () {var_this= This; varisbox1show= This. state.currentindex==1? ' Block ': ' None '; varisbox2show= This. state.currentindex==2? ' Block ': ' None '; varisbox3show= This. state.currentindex==3? ' Block ': ' None '; vartablist= This. State.tabs.map (function(res,index) {//traverse the tab, if the label's ID equals TabID, then the label adds one more active classname            vartabstyle=res.id== This. State.currentindex? ' Subctrl active ': ' Subctrl '; return<li Key={index} onclick={ This. Tabchoiced.bind (_this,res.id)} classname={tabstyle}>{res.tabname}</li>}.bind (_this)); return (            <div classname= "Listwrap" > <ul classname= "Subnavwrap" >{tabList}</ul> <div classname= "newslist" > <div style={{"display": Isbox1show}} >Social News</div> <div style={{"Display":isbox2show}}>Sports World</div> <div style={{"Display":isbox3show}}>Entertainment Circle</div> </div> </div>)}}exportdefaultNewslist;

Although this method is more fool-like, but very convenient. A little improvement on the basis of the first code. Judging the current currenindex is equal to a few, if it is 1, then the content page of the first display is set to block, the other content page display is noe. And so on Haha, really a little bit of a fool. It's good to do it.

Method 2: The form of a component, it can be said to write a small plug-in

Let's cut the crap.

varReact=require ("React");varReactdom=require ("React-dom"); class Tabscontrol extends react.component{constructor () {super ();  This. state={currentindex:0        }; } check_tittle_index (index) {returnindex=== This. State.currentindex? "Tab_tittle Active": "Tab_tittle"; } check_item_index (index) {returnindex=== This. State.currentindex? "Tab_item Show": "Tab_item"; } render () {Let _this= This; return(            <div>                {/*Dynamically generate tab navigation*/}                <div classname= "Tab_tittle_wrap" >{React.Children.map ( This. Props.children, (element,index) = {                        return(                            /*The arrow function does not have its own this, where this is inherited from the perimeter scope, that is, the component itself*/<div onclick={() = { This. setState ({Currentindex:index})}} classname={ This. Check_tittle_index (Index)}>{element.props.name}</div>                            ); }) }                </div> {/*Tab Content Area*/}                <div classname= "Tab_item_wrap" >{React.Children.map ( This. Props.children, (element,index) ={                        return(                            <div classname={ This. Check_item_index (Index)}>{element}</div>                            ); })}                </div> </div>            ); }}class Tabcomponent extends react.component{render () {return(            <div classname= "Container" > <TabsControl> <div name= "Social News" >the content of social news</div> <div name= "Sports World" >the content of the sports world</div> <div name= "Entertainment Circle" >content of the entertainment circle</div> </TabsControl> </div>            ); }}reactdom.render (<tabcomponent/>,document.getelementbyid ("app"));

This is a little bit more complicated, a little explanation, but if you read the previous two examples, it is very understood.

First we define a subassembly called Tabscontrol, and then we iterate over its sub-tags. Where does the content of the child tag come from, which is obtained from the name value inside the component.

  this.props.children is a react built-in property that gets the child elements of the component. Because the child element may be an object or an array,

So react provides some helper methods for handling children to traverse:React.Children.map。

For example, in the above code, This.props.children gets the inside of the three DIVD array, but if you just want a div, then you get the object. So need

React.Children.map () to coordinate the traversal.

Through this code above, we are very convenient to traverse. For example, a page needs to have more than one tab switch, then we just need to introduce this tabscontrol once.

Of course, my fool-like way is also very good. Haha, you like it.

If you think the article is useful, you can also give a small red packet to encourage encouragement, haha

React several ways to do tab switching

Related Article

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.