问题描述
因此,我们在这里进行Meteor和ReactJS的创新.这就是我所做的:
So here we are, innovating with Meteor and ReactJS. This is what i did:
- 在我的
client/lib/js/
文件夹中复制了mmenu jQuery插件. - 创建了一个名为
Menu
的组件,该组件在componentDidMount
方法中具有 mmenu 插件初始化. -
将React
Menu
放置在我的Layout
组件中,因此这是检查树时React树在Chrome中的外观:
- Copied the mmenu jQuery plugin inside my
client/lib/js/
folder. - Created a component called
Menu
which has the mmenu plugin initialization in thecomponentDidMount
method. Placed the React
Menu
in myLayout
component, so this how the React tree looked in Chrome when inspected:
<Layout> <Menu user={this.data.user} /> <Home /></Layout>
<Layout> <Menu user={this.data.user} /> <Home /></Layout>
问题是,当呈现Menu
组件时, mmenu 插件移动在React范围之外的相应DOM(nav
元素)(仅在下面) body
标记),因此当user
对象(作为道具传递)更改时,React尝试重新渲染该组件时,React会感到困惑.
Problem is, when the Menu
component renders, the mmenu plugin moves the corresponding DOM (the nav
element) outside of React scope (just bellow the body
tag), so React get confused when referencing that unexistent component when it tries to re-render it when user
object (passed as props) changes.
Menu
组件如下所示:
Menu = React.createClass({
componentDidMount(){
const menu = $(this.refs['mmenu']);
menu.mmenu({ /* some options here */ });
}
render(){
<nav id="menu" ref="mmenu">
{ this.props.user ? <HomePublic/> : <HomePrivate/> }
</nav>
}
});
如您所见,调用menu.mmenu()
函数时,插件将nav
元素移动到正文,如下所示:
As you can see, when invoking menu.mmenu()
function, the plugin moves the nav
element to the body, which looks like this:
<body>
<nav ...> </nav>
<div id="react-root"> ... </div>
</body>
所以我的问题是:有没有办法做到这一点,以便React可以无误地重新渲染组件?
So my question is: Is there a way to do this so React can re-render the component without errors?
推荐答案
答案是,在使用React时,根本不要使用jQuery(和插件).因为React处理它的虚拟DOM. jQuery Mmenu操纵Real DOM,因此这不能一起使用,React不适用于jQuery.
The answer is, not to use jQuery at all (and the plugins), when you are using React. Because React Handles its Virtual DOM. jQuery Mmenu manipulates the Real DOM, so this will not work together and React it is not designed to work with jQuery.
检查是否已经有一个ReactComponent,可用于解决任务.否则,如果您真的依赖jQuery,那么使用Blaze(就流星而言)可能会更好.
Check out, if there is a already a ReactComponent, which you could use to solve you task. Otherwise, if you really depend on jQuery, you are maybe better with Blaze (in terms of Meteor)
这篇关于如何将mmenu jQuery插件与ReactJS和Meteor集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!