在jsx的render函数中编写条件语句

Anu*_*thi 0 javascript jsx reactjs

我的状态是{visibilityFilter: "completed"}{visibilityFilter: "todo"}。基于此,我想为一个元素分配类名。像这样

<span {this.state.visibilityFilter=="completed"?className="active":className:""}>Completed</span>
Run Code Online (Sandbox Code Playgroud)

但这不起作用。我尝试了各种变化

{<span this.state.visibilityFilter=="completed"?className="active":className:"">Completed</span>}
Run Code Online (Sandbox Code Playgroud)

但是他们都没有工作。我知道,如果我在return语句外创建变量并将其分配为HTML,则它可以工作。像这样,

let classCompleted = this.state.visibilityFilter == "completed"? "active":"";
Run Code Online (Sandbox Code Playgroud)

然后,

<span className={`$(classCompleted)`}></span>
Run Code Online (Sandbox Code Playgroud)

但是我想知道如何在return语句中评估类。

T.J*_*der 5

您接近了,您只是将className零件放在外面:

<span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter.bind(this,'completed')}>Completed</span>
Run Code Online (Sandbox Code Playgroud)

题外注释:

每次使用bindin onClick意味着您将在每次渲染该元素时重新绑定。您可能考虑在组件的构造函数中执行一次:

class YourComponent extends React.Component {
    constructor(...args) {
        super(...args);
        this.handleFilter = this.handleFilter.bind(this);
        // ...
    }
    handleFilter() {
        // ...
    }
    render() {
        return <span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您已在转译器中启用了类属性(stage-2截至撰写本文时,它们位于Babel 的预设中,2017年1月),则另一个选择是使其成为箭头功能:

class YourComponent extends React.Component {
    // ...
    handleFilter = event => {
        // ...
    };
    render() {
        return <span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
    }
}
Run Code Online (Sandbox Code Playgroud)

那个例子:

<span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter.bind(this,'completed')}>Completed</span>
Run Code Online (Sandbox Code Playgroud)
class YourComponent extends React.Component {
    constructor(...args) {
        super(...args);
        this.handleFilter = this.handleFilter.bind(this);
        // ...
    }
    handleFilter() {
        // ...
    }
    render() {
        return <span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
    }
}
Run Code Online (Sandbox Code Playgroud)
class YourComponent extends React.Component {
    // ...
    handleFilter = event => {
        // ...
    };
    render() {
        return <span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @TJCrowder感谢您的回答和建议。 (2认同)