环顾四周,我无法找到答案:我如何动态地包含一个文件,基于每个说法的改变:这里有一些sudo代码,用于解释我想要做的事情!
class Test extends React.Component {
constructor(props){
super(props)
this.state = { componentIncluded: false }
includeFile() {
require(this.props.componetFileDir) // e.g. ./file/dir/comp.js
this.setState({ componentIncluded: true });
}
render() {
return(
<div className="card">
<button onClick={this.includeFile}> Load File </button>
{ this.state.componentIncluded &&
<this.state.customComponent />
}
</div>
)
}
}
所以this.props.componetFileDir
可以访问文件目录,但是我需要动态地包含它,并且在动作onClick
被调用之前似乎无法运行require() 。任何帮助都会很棒。
答案 0 :(得分:1)
在不同的情况下,您可以使用不同的React生命周期函数来注入组件。与componentWillReceiveProps或componentWillUpdate类似。
componentDidMount() {
// dynamically inject a Button component.
System.import('../../../components/Button')
.then((component) => {
// update the state to render the component.
this.setState({
component: component.default,
});
});
}
render() {
let Button = null;
if (this.state.component !== null) {
Button = this.state.component;
}
return (
<div>
{ this.state.component !== null ? <Button>OK</Button> : false }
</div>
);
}
编辑代码后,它应类似于以下内容:
class Test extends React.Component {
constructor(props){
super(props)
this.state = { customComponent: null }
this.includeFile = this.includeFile.bind(this);
}
includeFile() {
System.import(this.props.componetFileDir)
.then((component) => {
this.setState({ customComponent: component.default });
});
}
render() {
return(
<div className="card">
<button onClick={this.includeFile}> Load File </button>
{
this.state.customComponent
}
</div>
)
}
}