在 ReactJS 中显示/隐藏组件

IT技术 reactjs show-hide
2021-03-31 06:11:17

我们已经遇到了一些问题,在使用react过来,但现在它还挺归结到我们是如何被使用的react的一部分。

我们应该如何显示/隐藏子组件?

这就是我们对其进行编码的方式(这只是我们组件的片段)...

_click: function() {
  if ($('#add-here').is(':empty'))
    React.render(<Child />, $('#add-here')[0]);
  else
    React.unmountComponentAtNode($('#add-here')[0]);
},
render: function() {
  return(
    <div>
      <div onClick={this._click}>Parent - click me to add child</div>
      <div id="add-here"></div>
    </div>
  )
}

最近我一直在阅读这样的例子,它应该是这样的:

getInitialState: function () {
  return { showChild: false };
},
_click: function() {
  this.setState({showChild: !this.state.showChild});
},
render: function() {
  return(
    <div>
      <div onClick={this._click}>Parent - click me to add child</div>
      {this.state.showChild ? <Child /> : null}
    </div>
  )
}

我应该使用 React.render() 吗?它似乎阻止了像shouldComponentUpdate级联到孩子之类的各种事情e.stopPropagation......

2个回答

我提供了一个遵循您的第二种方法的工作示例。更新组件的状态是显示/隐藏子项的首选方式。

鉴于你有这个容器:

<div id="container">
</div>

您可以使用现代 Javascript(ES6,第一个示例)或经典 JavaScript(ES5,第二个示例)来实现组件逻辑:

使用 ES6 显示/隐藏组件

在 JSFiddle 上实时试用此演示

class Child extends React.Component {
  render() {
    return (<div>I'm the child</div>);
  }
}

class ShowHide extends React.Component {
  constructor() {
    super();
    this.state = {
      childVisible: false
    }
  }

  render() {
    return (
      <div>
        <div onClick={() => this.onClick()}>
          Parent - click me to show/hide my child
        </div>
        {
          this.state.childVisible
            ? <Child />
            : null
        }
      </div>
    )
  }

  onClick() {
    this.setState(prevState => ({ childVisible: !prevState.childVisible }));
  }
};

React.render(<ShowHide />, document.getElementById('container'));

使用 ES5 显示/隐藏组件

在 JSFiddle 上实时试用此演示

var Child = React.createClass({
  render: function() {
    return (<div>I'm the child</div>);
  }
});

var ShowHide = React.createClass({
  getInitialState: function () {
    return { childVisible: false };
  },

  render: function() {
    return (
      <div>
        <div onClick={this.onClick}>
          Parent - click me to show/hide my child
        </div>
        {
          this.state.childVisible
            ? <Child />
            : null
        }
      </div>
    )
  },

  onClick: function() {
    this.setState({childVisible: !this.state.childVisible});
  }
});

React.render(<ShowHide />, document.body);
只是一个关于 ternary 的注释something ? <Child /> : null,为什么不something && (<Child />)改用呢?昨天注意到这个,我很喜欢它
2021-05-26 06:11:17
@LarsBlumberg 是的,我在这里请你帮助我好吗。谢谢你。
2021-06-01 06:11:17
这真的很好。我想实现这一点。但是,如果单击子组件以外的其他组件,我还需要删除子组件。你能指导我怎么做吗?
2021-06-07 06:11:17
@MrMesees 我也喜欢这种情况下的 && 语法。
2021-06-07 06:11:17
@LarsBlumberg 我是 React 的新手,不了解这个核心概念。如果<Child/>是在许多不同的组件之间共享<Parents/>,使用这种设计,每个父级都必须实现显示和隐藏方法,从而造成大量代码重复。我已经考虑refs在我的项目中使用来避免这个问题 ( this.child.current.hide()) 但这似乎是不好的做法。您有解决代码重复问题的方法吗?
2021-06-13 06:11:17
    /* eslint-disable jsx-a11y/img-has-alt,class-methods-use-this */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import todoStyle from 'src/style/todo-style.scss';
import { Router, Route, hashHistory as history } from 'react-router';
import Myaccount from 'src/components/myaccount.jsx';

export default class Headermenu extends Component {

  constructor(){
  super();

  // Initial state
  this.state = { open: false };

}

toggle() {
  this.setState({
    open: !this.state.open
  });
}

  componentdidMount() {
    this.menuclickevent = this.menuclickevent.bind(this);
    this.collapse = this.collapse.bind(this);
    this.myaccount = this.myaccount.bind(this);
    this.logout = this.logout.bind(this);
  }

  render() {
    return (
      <div>

        <div style={{ textAlign: 'center', marginTop: '10px' }} id="menudiv" onBlur={this.collapse}>
          <button onClick={this.toggle.bind(this)} > Menu </button>

          <div id="demo" className={"collapse" + (this.state.open ? ' in' : '')}>
            <label className="menu_items" onClick={this.myaccount}>MyAccount</label>
            <div onClick={this.logout}>
              Logout
            </div>
          </div>

        </div>
      </div>
    );
  }

  menuclickevent() {
    const listmenu = document.getElementById('listmenu');
    listmenu.style.display = 'block';
  }



  logout() {
    console.log('Logout');
  }
  myaccount() {
    history.push('/myaccount');
    window.location.reload();

  }


}