1
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】フォームに値を入力しても表示されない(useState)

Posted at

はじめに

フォームに文字を入力しようとしても表示されなかった(同じ過ちを何度もしている)ため、備忘録で残します。

問題

フォームに値を入力しようとしても、表示されない。

image.png

function App() {
  const [text, setText] = useState('');
  const onChange = () => setText(text);

  return (
    <>
      <input value={text} onChange={onChange} />
      <br />
      <p>{text}</p>
    </>
  );
}

解決方法

setTextで設定している値が誤っていた。
onChange関数実行時のイベントからオブジェクト・プロパティ(e.target.value)を設定する。

image.png

function App() {
  const [text, setText] = useState('');
  const onChange = (e) => setText(e.target.value);

  return (
    <>
      <input value={text} onChange={onChange} />
      <br />
      <p>{text}</p>
    </>
  );
}

おわりに

onChangeイベントが発火した際に、なぜ引数にイベント(e)を設定、e.target.valueで指定しないといけないのか、根本的な理解をしたいです。

1
0
2

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
1
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?