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?

[React] Eventの設定方法

Last updated at Posted at 2024-11-25

環境

MacBook Pro (2.3 GHz 8コアIntel Core i9)
macOS 14.0(23A344)
Homebrew 4.3.8
gh 2.52.0

まとめ

  • React内にJavaScriptのイベント用の関数を埋め込む
  • HTMLにJavaScriptコードを埋め込む際は{}を用いる
e.g.
export const App = () => {
  const onClickButton = () => alert();
  return (
    <>
      <h1>こんにちは!</h1>
      <p>お元気ですか?</p>
+     {console.log(`hoge`)}
+     <button onclick={() => alert()}>ボタン</button>
    </>
  );
};

フォルダ構成

folda_structure
├── public/
│   ├── index.html
└── src/
│   ├── index.js(index.jsx)  (ここではインラインスタイルでCSSを記述)
│   └── App.js(App.jsx)      

ソースコード

index.js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

↓関数を外へ出し可読性を上げている

App.js
export const App = () => {
  const onClickButton = () => alert();
  return (
    <>
      <h1>こんにちは!</h1>
      <p>お元気ですか?</p>
      <button onclick={onClickButton}>ボタン</button>
    </>
  );
};

イメージ

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?