how to remove / unmount nested react components

a 夏天 提交于 2019-12-10 14:33:29

问题


I'd like to unmount a single react component, which belongs to a parent component containing three components total. The parent component has this render function:

render: function () {
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      <Home ref="home"/>
      <Footer ref="footer"/>
    </div>
),

handleNavbarClick: function () {
  // remove Home
}

if a user then clicks on a link in the navbar and I want to unmount the Home component, how would I do that? it seems like my only option is to do something like this (taken from react.js: removing a component), but this seems pretty gross:

render: function () {
  var home = this.state.remove_home ? null : <Home ref="home />
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {home}
      <Footer ref="footer"/>
    </div>
),

handleNavbarClick: function () {
  this.setState({remove_home: true});
}

Is that the appropriate react way to do things?


回答1:


Yes, your proposed solution of

render: function () {
  var home = this.state.remove_home ? null : <Home ref="home" />
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {home}
      <Footer ref="footer"/>
    </div>
),

handleNavbarClick: function () {
  this.setState({remove_home: true});
}

is more-or-less the "correct" way to handle this with React. Remember, the purpose of render is to describe the way your component should look at any given point. Reaching out to the DOM and performing manual operations, or doing other kind of imperative work like "removing" an element, is almost always the wrong thing to do.

If you're concerned about the syntax, you can consider inlining or extracting the logic:

render: function () {
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {this.state.remove_home ? null : <Home ref="home" />}
      <Footer ref="footer"/>
    </div>
),

or

render: function () {
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {!this.state.remove_home && <Home ref="home" />}
      <Footer ref="footer"/>
    </div>
),

or

render: function () {
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {this.renderHome()}
      <Footer ref="footer"/>
    </div>
),

renderHome: function() {
  if (!this.state.remove_home) {
    <Home ref="home" />
  }
}



回答2:


try this

handleNavBarClick: function(){
    React.findDOMNode(this.refs.home).style.display = 'none';
}


来源:https://stackoverflow.com/questions/30447767/how-to-remove-unmount-nested-react-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!