如何使用三元运算符在渲染函数中显示反应变量 [英] how to display react variable in render function using ternary operator

查看:81
本文介绍了如何使用三元运算符在渲染函数中显示反应变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不隐藏添加到输入标签?

why doesn't 'hidden' get added to the input tag?

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>


推荐答案

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

You can use inline styles to hide

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

或者您可以使用类来隐藏

Or you can use classes to hide

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

如果您只是不想渲染它

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

这篇关于如何使用三元运算符在渲染函数中显示反应变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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