也许添加另一个视角会有所帮助。您实际上需要在 JSX 中使用三元运算符是非常罕见的。在这种情况下,我会考虑将所有这些逻辑移到一个单独的函数中。
helperFunction: function() {
if(!this.state.msg) {
if(this.state.ask.length != 0) {
// return stuff
} else {
// return stuff
}
if(this....) {
// return stuff
} else {
// ...
}
} else {
// nothing
}
}
然后你就可以在你的渲染方法中使用你的辅助函数了。
React.createClass({
helperFunction: function() {
// ...
},
render: function() {
return (
<div>
{this.helperFunction()}
</div>
);
}
});
您的辅助函数可以返回可用于属性的值,也可以返回其他 JSX 组件。我经常发现将代码移出如下所示的模式很有帮助:
render: function() {
return (
condition === 'example' ?
<MyComponent attr={this.props.example} onChange={this.props.onChange} /> :
<MyOtherComponent attr={this.state.example} onChange={this.state.onChange}/>
);
}
如下代码:
helper: function(condition) {
if(condition === 'example') {
return (
<MyComponent attr={this.props.example} onChange={this.props.onChange} />
);
}
else {
return (
<MyOtherComponent attr={this.state.example} onChange={this.state.onChange}/>
);
}
},
render: function() {
return this.helper(condition);
}
在字符串相等检查的情况下甚至更好。
helper: function(condition) {
const default = <MyOtherComponent attr={this.state.example} onChange={this.state.onChange}/>
const conditions = {
example: <MyComponent attr={this.props.example} onChange={this.props.onChange} />,
example2: <MyComponent attr={this.props.example} onChange={this.props.onChange} />,
example3: <MyComponent attr={this.props.example} onChange={this.props.onChange} />,
};
return conditions[condition] || default;
},
render: function() {
return this.helper(condition);
}
这种方式为您提供了 switch 语句的大部分功能,但语法也更简洁,它可以让您从大量条件组件中优雅地进行选择。使用 if 语句(常规或三元)编写的相同代码会更加冗长。