programing

반응에서 구성 요소 표시/숨기기JS

kakaobank 2023. 3. 13. 20:37
반응형

반응에서 구성 요소 표시/숨기기JS

현재 리액트 사용에 몇 가지 문제가 발생하고 있지만 리액트 사용의 한 부분으로 귀결됩니다.

아동용 컴포넌트를 어떻게 표시/숨겼어야 했습니까?

이것은 델이 코드화한 방법입니다(이것은 델의 컴포넌트의 일부에 지나지 않습니다).

_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...

두 번째 접근법에 따른 작업 예를 제시했습니다.구성 요소의 상태를 업데이트하는 것이 하위 항목을 표시하거나 숨길 때 선호되는 방법입니다.

다음 컨테이너가 있는 경우:

<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);
    /* 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();

  }


}

언급URL : https://stackoverflow.com/questions/29913387/show-hide-components-in-reactjs

반응형