React 基本 Hooks 总结

import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useReducer,
  useRef,
  useState
} from "react";

export default function App() {
  return <h2>Hello, react hooks!</h2>
}

function TestFocus() {
  const ref = useRef();
  const WithRef = forwardRef(TestUseImperativeHandle);
  return (
    <>
      <button
        onClick={() => {
          ref.current.focus();
        }}
      >
        focus
      </button>
      <WithRef ref={ref} />
    </>
  );
}

function TestUseImperativeHandle(props, ref) {
  const refInput = useRef();

  useImperativeHandle(ref, () => {
    return {
      focus() {
        refInput.current.focus();
      }
    };
  });

  return <input ref={refInput} />;
}

function TestMemoDataUsage() {
  const [it, setIt] = useState(0);
  const info = useMemo(() => {
    return { name: "bob", age: 10 };
  }, []);

  return (
    <>
      <button
        onClick={() => {
          setIt(it + 1);
        }}
      >
        set it to {it}
      </button>
      <TestDepOnMemoData info={info} />
    </>
  );
}

function TestDepOnMemoData({ info }) {
  useEffect(() => {
    console.log("preparing info..", []);
  }, [info]);
  return <p>Hi, {JSON.stringify(info)}</p>;
}

function TestUseMemo() {
  const [easyThing, setEasyThing] = useState("easy thing");
  const hardThing = useMemo(() => {
    console.log("get something hard...");
    return "hard thing";
  }, []);

  return (
    <>
      <p>{hardThing}</p>
      <p>{easyThing}</p>
      <button
        onClick={() => {
          setEasyThing(easyThing + "-" + easyThing);
        }}
      >
        change easy thing
      </button>
    </>
  );
}

function TestUseReducer() {
  const [countState, dispath] = useReducer(
    (state, action) => {
      if (action.type === "inc") {
        return { count: state.count + 2 };
      }
      if (action.type === "dec") {
        return { count: state.count - 1 };
      }
    },
    { count: 0 }
  );

  return (
    <>
      <h2>Play hooks</h2>
      <div>
        <button
          onClick={() => {
            dispath({ type: "dec" });
          }}
        >
          -
        </button>
        <span>{countState.count}</span>
        <button
          onClick={() => {
            dispath({ type: "inc" });
          }}
        >
          +
        </button>
      </div>
    </>
  );
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值