Reactjs 如何在TSX中呈现由字符串确定的react组件
我想实现基于url哈希变化的导航 例如,对于url index.html#主页,应用程序将加载主页组件Reactjs 如何在TSX中呈现由字符串确定的react组件,reactjs,typescript,Reactjs,Typescript,我想实现基于url哈希变化的导航 例如,对于url index.html#主页,应用程序将加载主页组件 import { HomePage } from '../components/homepage' import { AnotherPage } from '../components/anoterpage' export class NavigationFrame extends React.Component<any, State> { constructor(pr
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";
}
}
从“../components/HomePage”导入{HomePage}
从“../components/AnotherPage”导入{AnotherPage}
导出类NavigationFrame扩展React.Component{
建造师(道具){
超级(道具);
this.state={pageName:this.pageNameFromUrl()};
}
onHashTagChanged=()=>{
this.setState({pageName:this.pageNameFromUrl()});
}
公共渲染(){
var Page=this.state.pageName,如有;
return//this.state.pageName=“HomePage”时呈现此属性;
}
}
有没有办法根据字符串动态创建组件?类CustomComponent扩展React.component{
class CustomComponent extends React.Component{
render(){
return (
var DynamicComponent = this.props.component;
return <DynamicComponent />;
)
}
}
render(){
返回(
var DynamicComponent=this.props.component;
返回;
)
}
}
将其导入到您的文件中并按如下方式使用
return (
<CustomComponent component={this.state.pageName} />
);
返回(
);
类CustomComponent扩展React.Component{
render(){
返回(
var DynamicComponent=this.props.component;
返回;
)
}
}
将其导入到您的文件中并按如下方式使用
return (
<CustomComponent component={this.state.pageName} />
);
返回(
);