我正在一个“模式窗口”(比如说)中进行一个Reactjs + React-motion项目,如果可能的话,我想动态地安装或加载一个组件?
到目前为止,我的解决方案是:我找不到方法,所以似乎很容易将组件放置到位,将其隐藏,然后在状态更改时切换类或样式,从而显示隐藏的组件,并且仅在“模式”之后窗口”转换完成。
在下面共享一些代码,可以更轻松地了解我要执行的操作。没有事件处理程序,大多数代码都已删除,但是onRest(暴露了动画结束时的事件回调)以及渲染fn。
onRest
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文档中有更多有关此的内容。请参阅此处的“有状态的孩子”部分:https : //facebook.github.io/react/docs/multiple- components.html