简体   繁体   English

React js:导入要路由的组件

[英]React js : import component to route

I have class like this in reactjs 我在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>)

    }
}

I am trying to load TopicDetails component in a route.The TopicDetails 我试图加载TopicDetails组件在route.The TopicDetails

topicDetails.js 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;  

My question is how can properly add the component which is imported?? 我的问题是如何正确添加导入的组件?

Since you are exporting TopicDetails as default export you can import it like 由于您将TopicDetails导出为默认导出,因此您可以像导入它一样

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

Complete code is here 完整的代码在这里

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>)

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM