我在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;
我的问题是如何正确添加导入的组件?
答案 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>)
}
}