Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React-子组件的自定义布局_Reactjs - Fatal编程技术网

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>
);