Reactjs React-子组件的自定义布局
我正在编写一个小部件库,我想让用户能够灵活地使用自己的布局。例如,我有一个Reactjs React-子组件的自定义布局,reactjs,Reactjs,我正在编写一个小部件库,我想让用户能够灵活地使用自己的布局。例如,我有一个跟踪器小部件,负责跟踪点的当前位置。以下是跟踪器的使用概述 <Tracker initialPos={[0,0]}> //<-- holds state of current position <TrackerPlot option={1} /> <TrackerPlot option={2} /> <TrackerPlot option={3} /&
跟踪器
小部件,负责跟踪点的当前位置。以下是跟踪器的使用概述
<Tracker initialPos={[0,0]}> //<-- holds state of current position
<TrackerPlot option={1} />
<TrackerPlot option={2} />
<TrackerPlot option={3} />
...
<TrackerPlot option={n} />
<TrackerControls />
</Tracker>
如果我可以灵活地添加周围的
,那么上面访问子对象的代码就会中断是否有一种模式/工具/设计允许用户使用子组件定义自己的布局这是一种经典用法,您的父母将是提供者,您的孩子将是消费者
// PosContext.jsx
export const PosContext = React.createContext({
pos: initialPosition
});
//Tracker.jsx
import {PosContext} from './PosContext';
export const Tracker = ({ initialPos, children }) => (
<PosContext.Provider value={{ pos: initialPos }}>{children}</PosContext.Provider>
);
// TrackerPlot.jsx
import { PosContext } from './PosContext';
export const TrackerPlot = props => (
<PosContext.Consumer>{({ pos }) => <div>{pos}</div>}</PosContext.Consumer>
);
//PosContext.jsx
export const PosContext=React.createContext({
位置:初始位置
});
//Tracker.jsx
从“/PosContext”导入{PosContext};
导出常量跟踪器=({initialPos,children})=>(
{儿童}
);
//TrackerPlot.jsx
从“/PosContext”导入{PosContext};
导出常量TrackerPlot=props=>(
{({pos})=>{pos}
);
function Tracker(props){
const [pos, setPos] = useState(props.initialPosition);
const children = React.Children.map(props.children, child=>{
return React.cloneElement(child, {
pos:pos
});
});
return {children};
}
// PosContext.jsx
export const PosContext = React.createContext({
pos: initialPosition
});
//Tracker.jsx
import {PosContext} from './PosContext';
export const Tracker = ({ initialPos, children }) => (
<PosContext.Provider value={{ pos: initialPos }}>{children}</PosContext.Provider>
);
// TrackerPlot.jsx
import { PosContext } from './PosContext';
export const TrackerPlot = props => (
<PosContext.Consumer>{({ pos }) => <div>{pos}</div>}</PosContext.Consumer>
);