后台:我使用ES6创建了一个使用React,Redux的工作应用程序。 Webpack用作CommonJS模式的捆绑器。
必需:我创建了另一个包含反应组件的文件。现在我想根据一些全局参数值切换组件。我在render方法中添加了一个if条件。请参阅下面的代码 -
const LPage = () => {
let resource = window.keys;
if(window.switchComponent == 0)
{
return (
<div className="container containerHome">
<div className="col-xs-12 col-sm-12 text-center">
<a className="logo spriteMobile"></a>
</div>
</div>
);
}
else
{
return window.AnotherComponent();
}
};
这适用于无状态组件。我不得不写这样的东西来使用外部组件。
window.React = React;
window.ReactDOM = ReactDOM;
现在我无法以这种方式替换有状态组件。他们必须解雇行动并更新商店。有没有办法用一些外部javascript替换/切换这些有状态组件?
答案 0 :(得分:0)
First off, window.AnotherComponent()
is not how you're supposed to instantiate components in React. The correct way here would be return <window.AnotherComponent />
. If you need to pass properties, you can do it as well: return <window.AnotherComponent foo={true}/>
Now, doing it the way you do it is very un-React-like. For once, in case the value of window.switchComponent
changes, your component will not be re-rendered, because React would have no way of knowing that the component's state has changed. There are other ways to provide global configuration values down the component trees, like for example setting them in the Redux store (which you already have set up anyway).