如何使用React JSX在条件下显示CSS:无? [英] How to CSS display:none within conditional with React JSX?

查看:225
本文介绍了如何使用React JSX在条件下显示CSS:无?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在用户点击链接时在同一页面上呈现 div

I'm trying to render a div on the same page when the user clicks on a link.

我的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:意外的令牌

SyntaxError: unknown: Unexpected token

对于这一行:

style={{display: { this.state.showStore ? 'block' : 'none'} }}

如何在一个样式中有条件地嵌套?

How can I nest conditionally inside a style?

推荐答案

这是因为三元运算符的使用不正确。请参阅此处的文档:
https://developer.mozilla.org/en/ docs / Web / JavaScript / Reference / Operators / Conditional_Operator

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

你不应该用 {} 正如你所做的那样。

You should not wrap it with {} as you have done.

尝试以下方法:

style={{display: this.state.showStore ? 'block' : 'none' }}

这篇关于如何使用React JSX在条件下显示CSS:无?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆