Reactjs: Pass same props to multiple components

前端 未结 1 1465
野性不改
野性不改 2021-01-27 05:08

I\'m kind of new to reactjs and I\'m trying to do a bit of clean up. I was wondering how I could use spread attributes for props provided by the new context api?

相关标签:
1条回答
  • 2021-01-27 05:25

    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>
    
    0 讨论(0)
提交回复
热议问题