reactjs,将道具从一个组件发送到另一个组件

时间:2019-09-27 16:55:54

标签: reactjs

我想将道具从组件A发送到组件B。我该怎么办? 顺便说一下,我正在使用react.lazy()

import React from 'react';

const CustomerList = React.lazy(() => 
import('./views/CustomerList/CustomerList'));
const CustomerDebt = React.lazy(() => 
import('./views/CustomerDebt/CustomerDebt'));
const routes = [
  { path: '/', exact: true, name: 'Home page' },
  { path: '/customerlist', name: 'Debt list', component: CustomerList},
  { path: '/customerdebt', name: 'Customer Debt', component: CustomerDebt},

1 个答案:

答案 0 :(得分:1)

在这种情况下,我从不使用React.lazy。但我可以为您推荐一种方法。 使用HOC传递道具。 创建HOC:

   const LazyHOC = ({ component: Component, ...rest }) => (
      <Suspense fallback={...}>
         <Component {...rest} />
      </Suspense>
   )

导入您的组件:

   const CustomerList = React.lazy(() => import('./views/CustomerList/CustomerList'));
   const CustomerDebt = React.lazy(() => import('./views/CustomerDebt/CustomerDebt'));

用HOC包装组件:

   const LazyCustomerList = props => <LazyHOC component={CustomerList} {...props}/>
   const LazyCustomerDebt = props => <LazyHOC component={CustomerDebt} {...props}/>

您可以传递以下道具:

   const routes = [
  { path: '/', exact: true, name: 'Home page' },
  { path: '/customerlist', name: 'Debt list', component: <LazyCustomerList props={...} />},
  { path: '/customerdebt', name: 'Customer Debt', component: <LazyCustomerDebt />},