Reactjs:将相同的道具传递给多个组件 [英] Reactjs: Pass same props to multiple components
本文介绍了Reactjs:将相同的道具传递给多个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 reactjs 有点陌生,我正在尝试做一些清理工作.我想知道如何为新上下文 api 提供的道具使用传播属性?<Today/>
和 <All/>
基本上会使用相同的道具,我觉得它看起来很乱.
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? <Today />
and <All />
will basically use the same props and I thought it looked pretty messy.
以下是我想要清理的行:
Here are the lines I wanted to clean up:
<ResultsProvider>
<ResultsContext.Consumer>
{(val) => (
<Switch>
<Route exact path={'/'} render={ (props) =>
<Today
results={val.results}
loading={val.loading}
viewTicket={val.viewTicket}
formatStatus={val.formatStatus}
fetchData={val.fetchData}
formatDate={val.formatDate}
sortResults={val.sortResults}
formatTitle={val.formatTitle}
/>
}/>
<Route path={'/week'} component={Week} />
<Route path={'/all'} render={ (props) =>
<All
results={val.results}
loading={val.loading}
viewTicket={val.viewTicket}
formatStatus={val.formatStatus}
fetchData={val.fetchData}
formatDate={val.formatDate}
sortResults={val.sortResults}
formatTitle={val.formatTitle}
/>
}/>
</Switch>
)}
</ResultsContext.Consumer>
</ResultsProvider>
推荐答案
由于两个组件都需要传递相同的 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>
这篇关于Reactjs:将相同的道具传递给多个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文