javascript - Reactjs - 组件作为道具
问题描述
因此,我使用和基于URL呈现不同的组件。但是,渲染时有很多相似的标记。所以,我创建了一个应该将组件作为道具并解决这个问题的方法!BrowserRouter
Route
Wrapper
class Wrapper extends React.Component {
componentDidMount() {
this.props.setActiveTab(this.props.activeTab);
console.log('Wrapper props: ', this.props)
}
render() {
const OtherComponent = this.props.otherComponent
return (
<Row>
<Col md='8' id='content-block'>
<SwitchTab />
</Col>
<Col md='4' id='info-block'>
<InfoComponent info={this.props.info} {...this.props}/>
{
this.otherComponent &&
<OtherComponent {...this.props}/>
}
</Col>
</Row>
)
}
}
这些是一些路线:
<Route
exact
path='/r/all/'
render={() =>
<Wrapper
setActiveTab={context.toggleTab}
activeTab={'3'}
info='all'
/>
}
/>
<Route
exact
path='/u/:username/'
render={(props) => {
return (
<Wrapper
setActiveTab={context.toggleTab}
activeTab={'4'}
info='user'
user={props.match.params.username}
otherComponent={Profile}
username={props.match.params.username}
/>
// <Profile username={props.match.params.username} />
)
}}
/>
<Route
exact
path='/r/:subreddit/'
render={(props) => {
return (
<Wrapper
setActiveTab={context.toggleTab}
activeTab={'4'}
info='subreddit'
otherComponent={Subreddit}
subreddit={props.match.params.subreddit}
/>
// <Subreddit subreddit={props.match.params.subreddit} />
)
}}
/>
otherComponent 没有被渲染。我不知道问题出在哪里。另外,如果有其他更好的方法,请说明。
解决方案
您this.otherComponent
在渲染之前检查是否真实。你只是想检查是否OtherComponent
真实。
{OtherComponent && <OtherComponent {...this.props} />}
如果您愿意,也可以更改Wrapper
为渲染。children
例子
class Wrapper extends React.Component {
componentDidMount() {
this.props.setActiveTab(this.props.activeTab);
console.log("Wrapper props: ", this.props);
}
render() {
const { children, ...restProps } = this.props;
return (
<Row>
<Col md="8" id="content-block">
<SwitchTab />
</Col>
<Col md="4" id="info-block">
<InfoComponent {...restProps} />
{children}
</Col>
</Row>
);
}
}
// Usage
<Wrapper>
<OtherComponent />
</Wrapper>
推荐阅读
- javascript - 无法在移动视图中隐藏 div
- angular - 在 Angular 7 中覆盖库组件的 HTML 模板
- python - 用函数根据特定分布生成随机数
- python - Python ConfigParser:输入节名称作为变量
- android - 如何一次从 JSON 对象中检索多个项目
- asp.net - log4net 写入“?” 当我使用 %type、%method 和 %line 模式时
- python - 下面的小 x 刻度,上面的主要
- php - 我正在尝试制作这个脚本,但正在向我展示这个问题
- c# - C# - 关闭其他进程的消息框
- php - Webpack 配置 html-webpack-plugin 与 PHP