【问题标题】:how to display react variable in render function using ternary operator如何使用三元运算符在渲染函数中显示反应变量
【发布时间】:2020-03-25 21:51:38
【问题描述】:

为什么不将“隐藏”添加到输入标签中?

class FontChooser extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hidden: true };
  }
  render() {
    console.log(this.state.hidden);

    return (
      <div>
        <input type="checkbox" id="boldCheckbox" {this.state ? 'hidden':'';}  />
       <button id="decreaseButton" hidden='true'>-</button>
        <span id="fontSizeSpan" hidden="true">
          {this.props.size}
        </span>
        <button id="increaseButton" hidden="true">
          +
        </button>
        <span id="textSpan">{this.props.text}</span>
      </div>
    );
  }
}

这是我的html:

<html>
  <head>
    <title>Font Chooser</title>
    <script src="react/react.js"></script>
    <script src="react/react-dom.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="FontChooser.js" type="text/jsx"></script>
  </head>
  <body>
    <div id="container"></div>

    <script type="text/jsx">

      ReactDOM.render(
      <div>
      <FontChooser min='4' max='40' size='16' text='Fun with React!' bold='false'/>
      </div>,
      document.getElementById('container'))
      ;
    </script>
  </body>
</html>

【问题讨论】:

  • 你希望 hidden 是 type 属性还是 class 属性的值?
  • 我只想将隐藏的词添加到输入标签,因为它不接受任何参数,如真或假
  • 完全隐藏,还是直接禁用?
  • 只是为了隐藏复选框

标签: javascript html css reactjs


【解决方案1】:

你可以使用内联样式来隐藏

<input type="checkbox" id="boldCheckbox" style={this.state.hidden ? {display: 'none'} : {} />

或者你可以使用类来隐藏

<input type="checkbox" id="boldCheckbox" className={this.state.hidden ? classes.hidden : ''} />

如果你只是不想渲染它

{!this.state.hidden &&
<input type="checkbox" id="boldCheckbox" />
}

【讨论】:

  • 好答案。他也可以把三元放在type属性中,所以type就是hidden或者checkbox
【解决方案2】:
<input type={this.state.hidden ? 'hidden' : 'checkbox'} id="boldCheckbox"  />

【讨论】:

  • 不起作用它添加了 class='hidden' 但我需要添加只是隐藏
【解决方案3】:
<input type="checkbox" id="boldCheckbox" {...this.state} />

<input type="checkbox" id="boldCheckbox" hidden={this.state.hidden} />

【讨论】:

  • @DCR “他们”是谁?什么是“更新帖子”?它与您的问题和我绝对准确的答案有什么关系?奇怪...
  • @DCR 您可以通过我在上面发布的 codepen 的链接来查看它是否有效,但如果您个人认为它不起作用 - 运气不好,谢谢您的提问
  • 你的例子没有反映这个问题。将 reatDOM.render 移动到 html 文件,你会发现你的答案不起作用,甚至对你也不行。
猜你喜欢
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 2019-02-22
  • 2022-01-04
  • 1970-01-01
相关资源
最近更新 更多