2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React classコンポーネントから関数コンポーネントにModalを変換する

Posted at

##今回使用するModalはこちら。
デモサイトはこちら

##クラスコンポーネントでの書き方

modal.jsx
import React from 'react';
import Rodal from 'rodal';
// include styles
import 'rodal/lib/rodal.css';
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { visible: false };
  }
  show() {
    this.setState({ visible: true });
  }
  hide() {
    this.setState({ visible: false });
  }
  render() {
    return (
      <div>
        <button onClick={this.show.bind(this)}>show</button>
        <Rodal visible={this.state.visible} onClose={this.hide.bind(this)}>
          <div>Content</div>
        </Rodal>
      </div>
    );
  }
}

関数コンポーネントでは、thisは使用できない。
パーツに分けて変換していこう!

###①Stateパーツ

【classComponent】this.state === 【functionComponent】 State

classComponent.jsx
 constructor(props) {
    super(props);
    this.state = { visible: false };
  }
functinComponent.jsx
 const [visible,setVisible] = useState(false);

###②handleパーツ
【classComponent】 this.setState === 【functionComponent】 handle

classComponent.jsx
show() {
    this.setState({ visible: true });
  }
  hide() {
    this.setState({ visible: false });
  }

functinComponent.jsx
   const modelHandleOpen = () => {
    setVisible(true);
  }
  const modelHandleClose = () => {
    setVisible(false);
  }

###③Contentsパーツ

classComponent.jsx
 <button onClick={this.show.bind(this)}>show</button>
   <Rodal visible={this.state.visible} onClose={this.hide.bind(this)}>
     <div>Content</div>
   </Rodal>
functinComponent.jsx
  <button className="navItemPopUp" onClick={modelHandleOpen}>アバウト<br/>
      <span><InsertEmoticonIcon/></span></button>
      <Rodal visible={visible} onClose={modelHandleClose}>
          <div>プロフィールの内容</div>
      </Rodal>
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?