로그인 사용자와 게스트 사용자를 조건을 통해서 element를 렌더링이 가능

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={false} />,
  document.getElementById('root')
);

login/logout 버튼 변경하기 상태에 따라 LogoutButton, LoginButton element를 button에 넣고 화면에 출력

class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;

    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} />
        {button}
      </div>
    );
  }
}

ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);

이렇게 분기하는게 좋을까? 분기를 해야하는 깊이가 커지면 모든 경우에 따라 처리를 해줘야 하겠구나. 두가지 조건이 있는 경우에는 두 조건의 조건부 렌더링을 해주는 컴포넌트(함수)를 만드는게 좋겠다.

버튼에 이벤트 핸들러 넣는 방법은 아래와 같음 

  1. 버튼을 만든다 (<button>
  2. 버튼을 클릭했을때 함수를 만든다 (handleClick)
  3. 버튼에 클릭할때 함수를 설정한다 (onClick)
  4. 바인딩 한다 (this.handleClick.bind(this))
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // 콜백에서 `this`가 작동하려면 아래와 같이 바인딩 해주어야 합니다.
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

 

 {this.state.isToggleOn ? 'ON' : 'OFF'}

 

+ Recent posts