Javascript React.js-从hoc向儿童传递道具
我一直在试着把我妈妈的一些道具传给孩子们。路由器交换机和路由。子组件中缺少道具。我使用React.CloneElement为孩子们添加道具,但似乎不起作用Javascript React.js-从hoc向儿童传递道具,javascript,reactjs,react-router,react-router-dom,Javascript,Reactjs,React Router,React Router Dom,我一直在试着把我妈妈的一些道具传给孩子们。路由器交换机和路由。子组件中缺少道具。我使用React.CloneElement为孩子们添加道具,但似乎不起作用 <BrowserRouter> <Layout> <React.Suspense fallback={loading()}> <Switch> <Route exact path="/" component={Login} /&g
<BrowserRouter>
<Layout>
<React.Suspense fallback={loading()}>
<Switch>
<Route exact path="/" component={Login} />
<Route path="/dashboard" component={Home} />
<Route path="/tickets" component={Tickets} />
</Switch>
</React.Suspense>
</Layout>
</BrowserRouter>
子组件没有得到数据道具,我只得到这个
{history: {…}, location: {…}, match: {…}, staticContext: undefined}
将
数据
道具注入基本组件的工作HOC示例
/*HOC*/
const with data=Base=>()=>
/*组成部分*/
类路由器扩展了React.Component{
render(){
返回this.props.data;
}
}
const RouterWithData=withData(路由器);//使用数据导出默认值(路由器);
ReactDOM.render(,document.getElementById('root'))代码>
将数据
道具注入基本组件的工作HOC示例
/*HOC*/
const with data=Base=>()=>
/*组成部分*/
类路由器扩展了React.Component{
render(){
返回this.props.data;
}
}
const RouterWithData=withData(路由器);//使用数据导出默认值(路由器);
ReactDOM.render(,document.getElementById('root'))代码>
此.props.children
是元素/组件的集合。因此,在调用cloneElement
之前,必须map
:
return React.Children.map(this.props.children, el => (
React.cloneElement(el, { data: 'ok' });
);
this.props.children
是元素/组件的集合。因此,在调用cloneElement
之前,必须map
:
return React.Children.map(this.props.children, el => (
React.cloneElement(el, { data: 'ok' });
);
使用HOC,您可以将道具传递给指导儿童
如果您需要将道具传递给更深层次的孩子,您可能需要使用
例如:
// LayoutContext.js
import React from 'react';
/**
* Create and initialize a context for the Layout component
*/
export default React.createContext({
data: null,
});
//App.js
从“React”导入React;
从“./Layout”导入布局;
导出默认函数App(){
返回(
{/*此树中的任何组件都可以使用LayoutContext*/}
);
}
使用HOC,您可以将道具传递给指导儿童
如果您需要将道具传递给更深层次的孩子,您可能需要使用
例如:
// LayoutContext.js
import React from 'react';
/**
* Create and initialize a context for the Layout component
*/
export default React.createContext({
data: null,
});
//App.js
从“React”导入React;
从“./Layout”导入布局;
导出默认函数App(){
返回(
{/*此树中的任何组件都可以使用LayoutContext*/}
);
}
// SomeChild.js
import React from 'react';
/**
* How you can consume the context in any child declared in the Layout component
* Here we are using the `useContext` hook but it works the same by using a Consumer
*/
export default function SomeChild() {
const { data } = React.useContext(LayoutContext);
// Do whatever you want with the data
}
// App.js
import React from 'react';
import Layout from './Layout';
export default function App() {
return (
<BrowserRouter>
<Layout>
{/* Any component in this tree can use the LayoutContext */}
</Layout>
</BrowserRouter>
);
}