Javascript 如何 CSS display:none 在条件内使用 React JSX?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37728951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to CSS display:none within conditional with React JSX?
提问by StandardNerd
I'm trying to render a div
on the same page when the user clicks on a link.
div
当用户单击链接时,我试图在同一页面上呈现 a 。
My HTML page:
我的 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>
My components/store.js.jsx
:
我的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>
);
}
});
But I get a:
但我得到一个:
SyntaxError: unknown: Unexpected token
语法错误:未知:意外的令牌
For this line:
对于这一行:
style={{display: { this.state.showStore ? 'block' : 'none'} }}
How can I nest conditionally inside a style?
如何有条件地嵌套在样式中?
回答by ctrlplusb
This is due to incorrect usage of the ternary operator. See documentation here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
这是由于三元运算符的错误使用造成的。请参阅此处的文档:https: //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
You should not wrap it with {}
as you have done.
你不应该{}
像你所做的那样把它包裹起来。
Try the following:
请尝试以下操作:
style={{display: this.state.showStore ? 'block' : 'none' }}
回答by 00500005
You can also conditionally create the element via
您还可以通过有条件地创建元素
{
this.state.showStore
? <div className="row account stores">
<div>a lot more divs</div>
</div>
: null
}
回答by cquezel
You can also change a classname and style in CSS.
您还可以在 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>
);
}
Note that it is generaly better to not use double curly braces {{ in render function as you are often creating a new object on every render execution. for example:
请注意,通常最好不要在渲染函数中使用双花括号 {{,因为您经常在每次渲染执行时创建一个新对象。例如:
{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}