const Tab = ({ children }) => {
const [activeIndex, setActiveIndex] = useState(0);
return (
<div>
{React.Children.map(children, (child, index) => {
return React.cloneElement(child, {
isActive: index === activeIndex,
onSelect: () => setActiveIndex(index)
});
})}
</div>
);
};
const TabItem = ({ isActive, onSelect, children }) => (
<div
onClick={onSelect}
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</div>
);
<Tab>
<TabItem>Tab 1</TabItem>
<TabItem>Tab 2</TabItem>
</Tab>
class Mouse extends React.Component {
state = { x: 0, y: 0 };
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
});
};
render() {
return (
<div onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
);
}
}
<Mouse render={({ x, y }) => (
<h1>鼠标位置: ({x}, {y})</h1>
)} />
function withLoading(Component) {
return function WithLoadingComponent({ isLoading, ...props }) {
if (isLoading) return <div>Loading...</div>;
return <Component {...props} />;
};
}
const UserListWithLoading = withLoading(UserList);
function ControlledInput() {
const [value, setValue] = useState('');
return (
<input
value={value}
onChange={e => setValue(e.target.value)}
/>
);
}
function UncontrolledInput() {
const inputRef = useRef();
const handleSubmit = () => {
console.log(inputRef.current.value);
};
return <input ref={inputRef} />;
}
const UserList = ({ users }) => (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
const UserListContainer = () => {
const { data, loading } = useFetch('/api/users');
if (loading) return <div>Loading...</div>;
return <UserList users={data} />;
};
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
export const useTheme = () => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
};