How to call an event on tabs changed in react-bootstrap

喜夏-厌秋 提交于 2019-12-12 11:58:09

问题


I've implemented Navigation Tabs in my React application using React-Bootstrap.

Like this:

<Tabs defaultActiveKey={1}>
    <Tab eventKey={1} title="Log in">
        {/* Irrelevant code */}
    </Tab>
    <Tab eventKey={1} title="Sign up">
        {/* Irrelevant code */}
    </Tab>
</Tabs>

Now on changing tabs I would like to call the following funtion:

changeTab(login) {
    if (login)
        this.setState({ heading: "Log in" })
    else
        this.setState({ heading: "Sign up" })
}

Where login is a Boolean that will be true for when the Log in tab is selected and false when the Sign up tab is selected.

How can I do that?

Edit:

I've figured out that you can call a function on when the tabs are clicked like this:

<Tabs defaultActiveKey={1} onClick={()=>this.changeTab()}>
    <Tab eventKey={1} title="Log in">
        {/* Irrelevant code */}
    </Tab>
    <Tab eventKey={1} title="Sign up">
        {/* Irrelevant code */}
    </Tab>
</Tabs>

But how can I know which tab was clicked? I need it to change the state based on which tab is clicked.


回答1:


I found a solution. You need to use onSelect in the Tabs component.

Like this:

<Tabs defaultActiveKey={1} onSelect={this.handleSelect()}>
    <Tab eventKey={1} title="Log in">
        {/* Irrelevant code */}
    </Tab>
    <Tab eventKey={1} title="Sign up">
        {/* Irrelevant code */}
    </Tab>
</Tabs>

And then make this your handleSelect function:

handleSelect(key) {
    if (key === 1)
        this.setState({ heading: "Log in" })
    else
        this.setState({ heading: "Sign up" })
}


来源:https://stackoverflow.com/questions/43214548/how-to-call-an-event-on-tabs-changed-in-react-bootstrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!