0
0

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 1 year has passed since last update.

ツールを使わないで React を使う方法

Last updated at Posted at 2022-02-11

参考ページ
既存のウェブサイトに React を追加する
こちらのサンプルを改造しました。
Multiple React components on a single HTML page

次のようなページを作成しました。
react_feb11_aa.png

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>グリムの昔話</title>
  </head>
  <body>
    <h2>簡単な React</h2>
    <blockquote>
    <p>このページはツールを使わないで React を使う例です。</p>
    <p>React はスクリプトタグとしてロードされます。</p>
    </blockquote>
    <p>
    KHM 21 灰かぶり
      <!-- We will put our React component inside this div. -->
      <div class="like_button_container" data-commentid="11"></div>
    </p>

    <p>
    KHM 53 白雪姫
      <!-- We will put our React component inside this div. -->
      <div class="like_button_container" data-commentid="12"></div>
    </p>

    <p>
    KHM 15 ヘンゼルとグレーテル
      <!-- We will put our React component inside this div. -->
      <div class="like_button_container" data-commentid="13"></div>
    </p>

    <hr />
    <blockquote>
	    Feb/11/2022<br />
    </blockquote>
    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>

    <!-- Load our React component. -->
    <script src="like_button.js"></script>

  </body>
</html>
like_button.js
'use strict';

const e = React.createElement;

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() {
    if (this.state.liked) {
	    const rvalue = 'あなたは ' + this.props.commentID + ' が好きです。';
      return rvalue
    }

    return e(
      'button',
      { onClick: () => this.setState({ liked: true }) },
      'すき'
    );
  }
}

// Find all DOM containers, and render Like buttons into them.
document.querySelectorAll('.like_button_container')
  .forEach(domContainer => {
    // Read the comment ID from a data-* attribute.
    const commentID = parseInt(domContainer.dataset.commentid, 10);
    ReactDOM.render(
      e(LikeButton, { commentID: commentID }),
      domContainer
    );
  });

ローカルでテストする方法

$ python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

ブラウザーで
http://0.0.0.0:8000/
にアクセス

image.png

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?