LoginSignup
0
0

[自分用]Next.jsのuse〜の初期値

Posted at

文字列の場合

※早速注意点だが、関数を記述する場所には注意(別の投稿に詳しく書いてあるよ)。

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

  return (
    <input type="text" value={text} onChange={e => {
      setText(e.target.value);
    }}/>
  );
}

valueのpropsを使うときは

onChange
inputに何かしらのテキストを打ったときにテキストが変更されるが、その時のイベントを取得することができる。
もしonChangeがない場合は、setTextで{text}を変えていないので、inputの中身が初期値のままになる。
※「set〜関数」を使って変数を変更しないと再レンダリングされないので気をつけよう!

逆にいうと、onChangeを使うと文字を入力したり、消したりするたびに再レンダリングされているのだ。

少しアレンジ

下記は5文字を超えたらアラートを出して、returnで処理を終了させている。

if(e.target.value.length > 5){
  alert('5文字以内にしてください');
  return;
}
setText(e.target.value);

下記のようにtrim()を追加すると、文字列の前後の空白を取り除いてくれる。

setText(e.target.value.trim());

真偽値

下記のコードは真偽値によって処理を与えるコード。

export default function Home() {
  const [foo, setFoo] = useState(1);
  const [isShow, setIsShow] = useState(true);

  const handleClick = () => {
    setFoo(foo => foo + 1);
  };

  return (
    <>
      {/* ここの三項演算子に注目 */}
      {true ? <h1>{foo}</h1> : null}
      <button
        onClick={handleClick}
      >
        ボタン
      </button>
      <button
        onClick={() => {
          setIsShow(false);
        }}
      >
        非表示
      </button>
    </>
  )
}

{true ? <h1>{foo}</h1> : null}
条件がtrueだったら「左 : 右」の左側が実行される。falseなら右側が実行される。
※jsxではreturnの中にif文を書くことができない。だから三項演算子を使うのだ。

<button onClick={() => { setIsShow(false); }} > 非表示 </buton>
そしてこのコードの解説。
まずsetIsShowの初期値には「true」が付与されている。そのため{true ? <h1>{foo}</h1> : null}の記述に基づき現在のカウントが表示されている。
「非表示」ボタンを押すとsetIsShowの中身が「false」に変わるためカウントが非表示になる。

これを「表示されているなら非表示に、非表示なら表示」という処理に変えたい!!!!

<button
  onClick={() => {
    setIsShow(false);
  }}
>
  非表示
</button>

{/* このコードを下記のように修正 */}

<button
  onClick={() => {
    setIsShow((isShow)=> !isShow);
  }}
>
  {isShow ? "非表示" : "表示"}
</button>

まずsetIsShowの中身を関数にすることで、前回の値を参照することができる。

また、!isShowは、tureならfalseを返し、falseならtrueを返す。
return isShow ? false : true;と同じ意味。

※そして毎度毎度のことだが、関数は外に出して使用しよう。上記は例なので中に書いている。
(useCallbackは忘れないようにね)

  const handleDisplay = useCallback(() => {
    setIsShow((isShow)=> !isShow);
  },[]);

  return (
    <>
      {isShow ? <h1>{foo}</h1> : null}
      <button
        onClick={handleClick}>
        ボタン
      </button>
      <button
        {/* ここがスッキリしました */}
        onClick={handleDisplay}
      >
        {isShow ? "非表示" : "表示"}
      </button>
    </>
  )
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