【问题标题】:add active class to selected item react将活动类添加到所选项目反应
【发布时间】:2017-08-12 00:53:57
【问题描述】:

我已经制作了一个反应父组件,如果用户单击两个选项之一,则会呈现不同的子组件。

根据选择的选项,我想添加一个active 类。

在下面查看我的代码。

我已经采取了很多方法,但由于我无法弄清楚,所以将它们剥离出来。

class Test extends Component {

    constructor(props) {
        super(props);

        this.state = {
            currentView: 'one'
        };

        this.showOne = this.showOne.bind(this);
        this.showTwo = this.showTwo.bind(this);
    }

    showOne() {
        this.setState({
            currentView: 'one'
        });
    }

    showTwo() {
        this.setState({
            currentView: 'two'
        });
    }

    render(){
    ......
        <p className="one" onClick={this.showOne}>One</p>
        <p className="two" onClick={this.showTwo}>Two</p>
    ......
    }
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你在寻找这样的东西吗?

    <p className={this.state.currentView === 'one' ? 'one active' : 'one'} onClick={this.showOne}>One</p>
    <p className={this.state.currentView === 'two' ? 'two active' : 'two'} onClick={this.showTwo}>Two</p>
    

    【讨论】:

    • 就是这样。多谢同胞! :-)
    • 如果可以使用 ES6 模板文字:className={ `one ${ this.state.currentView === 'one' ? ' active' : '' } },避免重复 one
    猜你喜欢
    • 2019-07-12
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    相关资源
    最近更新 更多