React 条件付きレンダリング、要素の非表示と表示

  • 「?」記号三項演算
​{ this.state.isShow ? <h2>既然是要成为一名正真的爱坤,那么请大声地喊出我们的爱坤口号!</h2>:null }
  • 「&&」と記号判定
{ this.state.isShow && <h2>我们的口号是唱跳rap篮球!</h2> }
  • className または style の css 属性の表示による非表示と表示
  constructor(props){
    super(props)
    this.state={
      isShow:true,
      H2style:{display: 'none'}
    }
  }

<h2 style={this.state.isShow ? null:this.state.H2style}>小黑子终于漏出鸡脚了吧</h2>
  • また、リッチテキスト挿入用のdangerouslySetInnerHTMLを使用して、表示と非表示を切り替えることもできます。
 <h2 dangerouslySetInnerHTML={ {__html: this.state.isShow ? '正真的爱坤没有口号,真正的爱坤都是爱在心里的':null} }></h2>

コード例:

import React, { Component } from 'react'

export default class App extends Component {

  constructor(props){
    super(props)
    this.state={
      isShow:true,
      H2style:{display: 'none'}
    }
  }

  render() {
    return (
      <div>
        <button onClick={()=>{this.ikunFun()}}>点击</button>
        { this.state.isShow ? <h2>既然是要成为一名正真的爱坤,那么请大声地喊出我们的爱坤口号!</h2>:null }
        { this.state.isShow && <h2>我们的口号是唱跳rap篮球!</h2> }
        <h2 style={this.state.isShow ? null:this.state.H2style}>小黑子终于漏出鸡脚了吧</h2>
        <h2 dangerouslySetInnerHTML={ {__html: this.state.isShow ? '正真的爱坤没有口号,真正的爱坤都是爱在心里的':null} }></h2>
      </div>
    )
  }
  
  ikunFun(){
    this.setState({
      isShow:!this.state.isShow
    })
  }

}

おすすめ

転載: blog.csdn.net/qq_46149597/article/details/129181394