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】【例】 クラスコンポーネントから関数コンポーネントへ書き換え

Last updated at Posted at 2024-04-09

クラスコンポーネント


import React, { Component } from "react";

class Text extends Component {
  render() {
    const text = this.props.text;

    return <div style={{ color: "green" }}>{text}</div>;
  }
}

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: ""
    };
  }

  render() {
    const text = this.state.text;

    return (
      <div>
        <h1>
          <Text text={text} />
        </h1>
        <input
          type="text"
          value={text}
          onChange={e => {
            this.setState({
              text: e.target.value
            });
          }}
        />
      </div>
    );
  }
}

関数コンポーネント


import React, { useState } from "react";

function Text(props) {
  return <div style={{ color: "green" }}>{props.text}</div>;
}

export default function App() {
  const [text, setText] = useState("");

  return (
    <div>
      <h1>
        <Text text={text} />
        入力して下さい
      </h1>
      <input
        type="text"
        value={text}
        onChange={e => {
          setText(e.target.value);
        }}
      />
    </div>
  );
}
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?