Javascript 是'+;((可见“是活动的”)x27;好的做法?
我正在写一个奇特的登录模式,遇到了一个令人困惑的问题。我需要在React中切换模态。并认为这是最优雅的方式。但它安全吗?或良好做法Javascript 是'+;((可见“是活动的”)x27;好的做法?,javascript,reactjs,Javascript,Reactjs,我正在写一个奇特的登录模式,遇到了一个令人困惑的问题。我需要在React中切换模态。并认为这是最优雅的方式。但它安全吗?或良好做法 className={ 'modal ' + ((this.state.showLoginModal && 'is-active') || '') } 我希望这在某些浏览器上不会失败。它目前可以工作。然后,有时,有人想反转逻辑并交换两个字符串: ((this.state.showLoginModal && '') || 'is-
className={ 'modal ' + ((this.state.showLoginModal && 'is-active') || '') }
我希望这在某些浏览器上不会失败。它目前可以工作。然后,有时,有人想反转逻辑并交换两个字符串:
((this.state.showLoginModal && '') || 'is-active')
沃伊拉,它坏了。我更喜欢三元结构,因为它更容易理解,也更防弹:
this.state.showLoginModal ? "is-active" : ""
使用这种语法完全可以,但我更喜欢使用ES6中的记号和三元运算符:
className={`modal ${this.state.showLoginModal ? 'is-active' : ''}`}
为什么不简单地使用三元,这样更容易阅读和理解
className={ 'modal ' + (this.state.showLoginModal ? 'is-active' : '') }
作为一个可选的建议,如果你发现自己在这个地方做了这类事情,那么考虑使用一个更干净的API <
// 'is-active' if true, '' if false
classNames({
'is-active': this.state.showLoginModal
});
不,这是一个可怕的模式。使用适当的条件运算符。