我尝试将上下文api与useState挂钩一起使用。我无法与打字稿:(
首先创建App.tsx:
const App = () => {
const [exampleId, updateExampleId] = useState(0);
return (
<div>
<ExampleContext.Provider value={ [exampleId, updateExampleId]}>
<ExampleList/>
</ExampleContext.Provider>
</div>
);
}
export default App;
然后我添加了ExampleList.tsx:
function ExampleList() {
const {exampleId, updateExampleId} = useContext(ExampleContext);
const handleListItemClick = (
event: React.MouseEvent<HTMLDivElement, MouseEvent>,
id: number,
) => {
// How can I call updateExample to set id to exampleId?
updateExampleId();
};
return (
<List component="nav">
{examples.map((example) =>
<ListItem button
key={example.id}
selected={...}
onClick={event => handleListItemClick(event, example.id)}>
<ListItemText
Example Text
/>
</ListItem>
)
}
</List>
);
也有上下文。如何创建类型化上下文?有必要吗?我试图这样使用它:
export interface ContextType {
exampleId: number,
updateExampleId: (value: number) => {}
}
// React.createContext< ContextType > ???
export const ExampleContext = React.createContext({
exampleId: 0,
updateExampleId: () => {}
});
export default ExampleContext ;
答案 0 :(得分:0)
也许<ExampleContext.Provider value={ {exampleId, updateExampleId} }>