我正在开发一个 Reactjs + React-motion 项目,在一个“模态窗口”(比方说)中,我想动态安装或加载一个组件,如果可能的话?
到目前为止我的解决方案:我找不到方法,所以似乎更容易将组件放置到位并隐藏它,然后在状态更改时切换类或样式,仅在之后显示隐藏的组件“模态窗口”转换完成。
在下面分享一些代码,可以更容易地理解我想要做什么。没有事件处理程序,并且大多数代码已被删除,但 onRest
(动画完成时的事件回调被公开)以及渲染 fn。
class HomeBlock extends React.Component {
constructor (props) {
...
}
...
motionStyleFromTo () {
return {
...
};
}
onRest () {
// this is triggered when the Motion finishes the transition
}
render () {
return (
<Motion onRest={this.onRestCallback.bind(this)} style={this.motionStyleFromTo()}>
{style =>
<div className="content" style={{
width: `${style.width}px`,
height: `${style.height}px`,
top: `${style.top}px`,
left: `${style.left}px`
}}>
[LOAD COMPONENT HERE]
</div>
}
</Motion>
);
}
}
export default HomeBlock;
最佳答案
你可以很容易地实现这一点。在此示例中,我根据 prop 动态渲染组件:
class MyComponent extends React.Component {
propTypes: {
display: React.PropTypes.bool
},
render() {
return (
<div>
{this.props.display ? <ChildComponent /> : null}
</div>
)
}
}
根据您的情况,您可能希望使用内部组件状态来安装或卸载组件。
仅供引用,在某些情况下您可能更喜欢或需要使用样式来隐藏组件而不是销毁它们。 React 文档中有更多相关内容。请参阅此处的“有状态 child ”部分:https://facebook.github.io/react/docs/multiple-components.html
关于javascript - 如何在reactjs中动态加载组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36941829/