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>
</>
);
}
React 基本 Hooks 总结
最新推荐文章于 2022-12-08 22:00:48 发布