有条件根据父状态显示徽标A或徽标B

时间:2018-12-01 23:21:30

标签: html reactjs

我有一个菜单,如果切换开关为“打开”,我想显示一个大徽标,如果切换开关为“闭合”,我想显示一个小徽标。无法从子“徽标”组件“监视”父状态的概念。

import React, { Component } from 'react'
import Logo from './Logo'
import Nav from './Navbar'
import Meta from './Meta'
import HeaderStyle from './Header.css'

class Header extends Component {
  constructor() {
    super()
    this.state = {
      isToggleOn: false
    }

    // Bind function (updateState) to class (Header)
    this.updateState = this.updateState.bind(this)
  }

  updateState() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }))
  }

  render() {
    return(
      <header>
        <Logo />
        <Nav />
        <Meta />
        <button onClick={this.updateState}>
          {this.state.isToggleOn ? 'CLOSE' : 'OPEN'}
        </button>
      </header>
    )
  }
}

export default Header
import React, { Component } from 'react'
import LogoImg from '../../img/logo.png'
import LogoMinImg from '../../img/logo-min.png'

class Logo extends Component {
  render() {
    return(
      <div className="logo-wrap">
        <img src={this.state.isToggleOn ? LogoImg : LogoMinImg} className="logo" alt=""/>
      </div>
    )
  }
}

export default Logo

1 个答案:

答案 0 :(得分:1)

您没有将isToggleOn道具传递给Logo组件。如果父母重新渲染,孩子也将重新渲染。

<Logo isToggleOn={this.state.isToggleOn} />

,然后在Logo中:

<img src={this.props.isToggleOn ? LogoImg : LogoMinImg} className="logo" alt="" />