且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Reactjs:将相同的道具传递给多个组件

更新时间:2023-02-11 14:26:04

由于两个组件都需要传递相同的 props,你可以创建一个对象,然后使用像

Since both the components need to be passed the same props, you can create an object and then pass it to the components using spread syntax like

<ResultsProvider>
    <ResultsContext.Consumer>
      {(val) =>  {
        const customProps = {
           results: val.results,
           loading: val.loading,
           viewTicket: val.viewTicket,
           formatStatus: val.formatStatus,
           fetchData: val.fetchData,
           formatDate: val.formatDate,
           sortResults: val.sortResults,
           formatTitle: val.formatTitle
        }
       return  <Switch>
          <Route exact path={'/'} render={ (props) =>
              <Today
                {...props}
                {...customProps}
              />
          }/>
          <Route path={'/week'} component={Week} />
          <Route path={'/all'} render={ (props) => 
              <All
                {...props}
                {...customProps}
              />
          }/>
        </Switch>
      }}
    </ResultsContext.Consumer>
  </ResultsProvider>