ref不起作用(反应js)

时间:2018-07-01 15:30:52

标签: reactjs ref

嘿,我阅读了ref doc(https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element)并试图做同样的事情,但是尽管添加了相同的行,但还是行不通的:

import React from 'react'
import './Nav.css'
import {NavLink} from 'react-router-dom'
import Cookies from 'js-cookie'
import Logo from './Logo'

class Nav extends React.Component {
  constructor(props) {
    super(props)
    this.textInput = React.createRef(); //// I INIT MY REF ////
    this.state = {
      showCategory: false
    }

    this.displayMenu = this.displayMenu.bind(this);
    this.closeMenu = this.closeMenu.bind(this);
    this.logOutKillCookie = this.logOutKillCookie.bind(this);
  }

  displayMenu() {
    this.setState({ showCategory: true }, () => {
      document.addEventListener('click', this.closeMenu)
    })
  }

  closeMenu(event) {
    console.log(event.target, this.dropdownMenu)
    if (!this.textInput.contains(event.target)) { //// ERROR BECAUSE this.textInput IS NULL ////
      this.setState({ showCategory: false }, () => {
        document.removeEventListener('click', this.closeMenu)
      })
    }
  }

  componentDidMount() {
    console.log(this.textInput) //// RENDER ME NULL... ////
  }

  logOutKillCookie() {
    Cookies.remove('id')
    Cookies.remove('username')
  }
  render() {
    return (
      <div id='Nav_wrapper'>
        <Logo className='Nav_logo'/>
        <div id='Nav_trigram' onClick={this.displayMenu}>{'\u2630'}</div>
      {(this.state.showCategory) ? (
        <div id='Nav_menu' ref={this.textInput}> //// I SET THE REF VALUE ////
          <NavLink id='Nav_match' className='Nav_category' exact to='/' activeClassName={'Nav_clicked'}>Match</NavLink>
          <NavLink id='Nav_chat' className='Nav_category' exact to='/chat' activeClassName={'Nav_clicked'}>Chats</NavLink>
          <NavLink id='Nav_profil' className='Nav_category' exact to='/profil' activeClassName={'Nav_clicked'}>Profil</NavLink>
          <a href='/' id='Nav_logOut' className='Nav_category' onClick={this.logOutKillCookie}>LogOut</a>
        </div>
      ) : null}
      </div>
    );
  }
}
export default Nav;

希望有人可以提供帮助并向我解释我的错误在哪里。谢谢!

1 个答案:

答案 0 :(得分:1)

没有引用,导致呈现条件的原因:

{(this.state.showCategory) ? 

并且初始状态showCategory = false,因此没有ref处于组件安装状态且ref为null的div。