import { useState } from 'react';
interface State {
count: number;
}
function Counter() {
const [state, setState] = useState({ count: 0 });
return (
Count: {state.count}
);
}
import { useEffect, useState } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
// 模拟数据获取
setTimeout(() => {
setData('Fetched data!');
}, 1000);
}, []); // 空数组表示只在组件挂载时运行
return (
Data: {data}
);
}
import { createContext, useContext } from 'react';
interface ContextValue {
value: string;
}
const MyContext = createContext({ value: 'Default Context Value' });
function ContextConsumer() {
const contextValue = useContext(MyContext);
return (
Context Value: {contextValue.value}
);
}
import { useReducer } from 'react';
interface State {
count: number;
}
type Action = { type: 'increment' };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
}
function ReducerExample() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
Count: {state.count}
);
}
import { useCallback, useState } from 'react';
function CallbackExample() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount((prevCount) => prevCount + 1);
}, []);
return (
Count: {count}
);
}
import { useMemo, useState } from 'react';
function MemoExample() {
const [a, setA] = useState(1);
const [b, setB] = useState(2);
const result = useMemo(() => {
console.log('Computing result...');
return a + b;
}, [a, b]);
return (
Result: {result}
);
}
import { useEffect, useRef } from 'react';
function RefExample() {
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
return (
);
}
import { forwardRef, useImperativeHandle, useRef } from 'react';
interface MyComponentProps {
// Props definition
}
interface MyComponentMethods {
focus: () => void;
// Other exposed methods
}
const MyComponent = forwardRef((props, ref) => {
const internalRef = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => {
if (internalRef.current) {
internalRef.current.focus();
}
},
// Other exposed methods or values
}), []);
return (
);
});
// Usage
function ImperativeHandleExample() {
const myRef = useRef(null);
useEffect(() => {
if (myRef.current) {
myRef.current.focus();
}
}, []);
return (
);
}