首页 > 解决方案 > Reactjs - 组件作为道具

问题描述

因此,我使用和基于URL呈现不同的组件。但是,渲染时有很多相似的标记。所以,我创建了一个应该将组件作为道具并解决这个问题的方法!BrowserRouterRouteWrapper

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 没有被渲染。我不知道问题出在哪里。另外,如果有其他更好的方法,请说明。

标签: javascriptreactjs

解决方案


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>

推荐阅读