也許這會幫助增加另一個視角。實際上,需要才能在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語句(常規或三元)編寫的代碼將更加冗長。
只是取代說如果與「?「然後用」:「。OI會爲你寫信 – Casey
你原來的代碼不是」三元「的,因爲最初的'if'沒有'else'。 – 2015-10-16 16:57:09
true我編輯過了,但仍然不工作 –