是否可以将组件提取出来放在CustomComponent/states 内,然后自己(CustomComponent)以及子组件们(components/xxx)都可以共用呢?
有如下的自定义组件CustomComponent(包含自己需要的子组件们components):
.CustomComponent
|
|--- index.tsx
|--- index.css
\--- components
|
|--- Modal.tsx
|--- Backdrop.tsx
\--- Todo.tsx
我使用的是zustand 状态管理器,我知道可以把组件 CustomComponent 的状态放到全局去,但是肯定没有放在组件内好。但是我觉得将状态放在CustomComponent/index.tsx 中也不好,不方便子组件进行访问。请问下,是否可以将组件提取出来放在CustomComponent/states 内,然后自己(CustomComponent)以及子组件们(components/xxx)都可以共用呢?
回复
1个回答
test
2024-07-02
你可以在CustomComponent/states里新建一个 Zustand store
// CustomComponent/states/index.ts
import create from 'zustand';
interface State {
count: number;
increase: () => void;
}
export const useStore = create<State>((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
}));
然后在CustomComponent和它子组件里用这个 store:
// CustomComponent/index.tsx
import React from 'react';
import { useStore } from './states';
import Modal from './components/Modal';
const CustomComponent: React.FC = () => {
const { count, increase } = useStore();
return (
<div>
<p>Count: {count}</p>
<button onClick={increase}>Increase</button>
<Modal />
</div>
);
};
export default CustomComponent;
CustomComponent/components/Modal.tsx
import React from 'react';
import { useStore } from '../states';
const Modal: React.FC = () => {
const { count, increase } = useStore();
return (
<div>
<p>Modal Count: {count}</p>
<button onClick={increase}>Increase in Modal</button>
</div>
);
};
export default Modal;
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容