在呈现路由后,将JavaScript应用于React中的布局



使用Meteor 1.4、Flow Router和React,我需要执行一些JavaScript代码来初始化布局。目前,我有这个

FlowRouter.route('/', {
  name: 'Home',
  action() {
    mount(MainLayout, {
      content: <div>Home</div>
    });
  }
});

我需要执行这个

$(function () {
  $('.button-collapse').sideNav();
  $('.parallax').parallax();
});

在布局HTML上。这段代码应该在每次渲染MainLayout时执行,并且在其他路由中将使用相同的布局(显然!)。

布局初始化代码应该放在哪里?

将其放入组件的componentDidMount函数中:

class MainLayout extends React.Component {
  componentDidMount() {
    $('.button-collapse').sideNav();
    $('.parallax').parallax();  
  }
}

除非你想在更新时重新运行这些(比如当包括孩子在内的道具发生变化时):

class MainLayout extends React.Component {
  componentDidMount() {
    this.isMounted = true; 
    this.initialiseJQueryWidgets();
  }
  componentDidUpdate() {
    if (this.isMounted) // In case you're doing server-side rendering
      this.initialiseJQueryWidgets();
  }
  initialiseJQueryWidgets() {
    $('.button-collapse').sideNav();
    $('.parallax').parallax();  
  }
}

最新更新