如何使用三元运算符在渲染函数中显示react变量

IT技术 javascript html css reactjs
2021-05-02 06:52:30

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

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>
3个回答

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

<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" />
}
<input type={this.state.hidden ? 'hidden' : 'checkbox'} id="boldCheckbox"  />
<input type="checkbox" id="boldCheckbox" {...this.state} />

或者

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