使用useContext钩子函数实现在React中添加和删除数据,以及对数量进行计数。
import { createContext } from 'react';
export interface Data {
id: number;
name: string;
}
export interface ContextProps {
data: Data[];
addData: (name: string) => void;
removeData: (id: number) => void;
count: number;
}
export const AppContext = createContext({
data: [],
addData: () => {},
removeData: () => {},
count: 0,
});
import React, { useState } from 'react';
import { AppContext, Data, ContextProps } from './AppContext';
interface Props {
children: React.ReactNode;
}
const AppProvider = ({ children }: Props) => {
const [data, setData] = useState([]);
const [count, setCount] = useState(0);
const addData = (name: string) => {
const newData: Data = {
id: data.length + 1,
name,
};
setData([...data, newData]);
setCount(count + 1);
};
const removeData = (id: number) => {
const updatedData = data.filter(item => item.id !== id);
setData(updatedData);
setCount(count - 1);
};
const contextValue: ContextProps = {
data,
addData,
removeData,
count,
};
return (
{children}
);
};
export default AppProvider;
import React from 'react';
import AppProvider from './AppProvider';
import DataList from './DataList';
import DataForm from './DataForm';
const App = () => {
return (
My App
);
};
export default App;
import React, { useContext } from 'react';
import { AppContext } from './AppContext';
const DataList = () => {
const { data, removeData } = useContext(AppContext);
return (
<
相关内容