我正在尝试在用户点击链接时在同一页面上呈现div
。
我的HTML页面:
<div class="stores">
<h1>Stores</h1>
<ul class="stores">
<li><a href="#" onClick={this.onClick} >Store A</a></li>
<li>Store B</li>
<li>Store C</li>
</ul>
</div>
我的components/store.js.jsx
:
var Store = React.createClass({
getInitialState: function() {
return { showStore: false };
},
onClick: function() {
this.setState({ showStore: true });
},
render: function() {
return(
<div className="row account stores" style={{display: { this.state.showStore ? 'block' : 'none'} }}>
<div>a lot more divs</div>
</div>
);
}
});
但我得到一个:
SyntaxError:unknown:意外的令牌
对于这一行:
style={{display: { this.state.showStore ? 'block' : 'none'} }}
如何在一个风格中有条件地嵌套?
这是由于三元运算符的使用不正确。请参阅此处的文档:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
你不应该像你一样用{}
包装它。
请尝试以下方法:
style={{display: this.state.showStore ? 'block' : 'none' }}
您还可以通过有条件地创建元素
{
this.state.showStore
? <div className="row account stores">
<div>a lot more divs</div>
</div>
: null
}
您还可以在CSS中更改类名和样式。
// outside render
const NORMAL = "row account stores"
const HIDDEN = NORMAL + " hidden"
// In render
render: function() {
return(
<div className={this.state.showStore ? NORMAL : HIDDEN}>
<div>a lot more divs</div>
</div>
);
}
请注意,通常最好不要使用双花括号{{在渲染函数中,因为您经常在每次渲染执行时创建一个新对象。例如:
{display: true ? 'block' : 'none' } === {display: true ? 'block' : 'none' } // false
// outside render
const BLOCK = {diplay: 'block'}
const NONE= {diplay: 'none'}
// in render
{this.state.showStore ? BLOCK : NONE}