React js:导入要路由的组件

时间:2018-10-16 13:19:34

标签: javascript reactjs react-router-v4

我在reactjs中有这样的课程

class Topics extends React.Component {

    constructor(props){
        super(props);
        this.state ={
            url:props.match.url,
            path:props.match.path
        }
    }
    render(){

        return (<div>
        <h2>Topic</h2>
        <ul>
          {topics.map(({ name, id }) => (
            <li key={id}>
              <Link to={`${this.state.url}/${id}`}>{name}</Link>
            </li>
          ))}
        </ul>
        <Route path={`${this.state.path}/:topicId`} component={TopicDetails}/>
      </div>)

    }
}

我正在尝试在路由中加载TopicDetails组件。TopicDetails

topicDetails.js

const TopicDetails = ({match}) => {
    const topic = topics.find(({ id }) => id === match.params.topicId);

    return (<div>
        <h2>Details</h2>
        <h2>{topic.name}</h2>
      <p>{topic.description}</p>

      </div>
      )

    }


export default TopicDetails;  

我的问题是如何正确添加导入的组件?

1 个答案:

答案 0 :(得分:3)

由于您将TopicDetails导出为默认导出,因此可以将其导入

import TopicDetails from './TopicDetails'; //here specify the correct path of TopicDetails functional component

完整的代码在这里

import TopicDetails from './TopicDetails';
class Topics extends React.Component {

    constructor(props){
        super(props);
        this.state ={
            url:props.match.url,
            path:props.match.path
        }
    }
    render(){

        return (<div>
        <h2>Topic</h2>
        <ul>
          {topics.map(({ name, id }) => (
            <li key={id}>
              <Link to={`${this.state.url}/${id}`}>{name}</Link>
            </li>
          ))}
        </ul>
        <Route path={`${this.state.path}/:topicId`} component={TopicDetails}/>
      </div>)

    }
}