我想根据网址中的哈希变化实现导航。
例如对于url index.html#HomePage,应用程序将加载HomePage组件。
import { HomePage } from '../components/homepage'
import { AnotherPage } from '../components/anoterpage'
export class NavigationFrame extends React.Component<any, State> {
constructor(props) {
super(props);
this.state = { pageName: this.pageNameFromUrl() };
}
onHashTagChanged = () => {
this.setState({pageName: this.pageNameFromUrl()});
}
public render() {
var Page = this.state.pageName as any;
return <Page /> //this renders <homepage /> when this.state.pageName = "HomePage";
}
}
有没有办法如何根据字符串动态创建组件?
答案 0 :(得分:1)
class CustomComponent extends React.Component{
render(){
return (
var DynamicComponent = this.props.component;
return <DynamicComponent />;
)
}
}
将其导入您的文件并使用如下,
return (
<CustomComponent component={this.state.pageName} />
);