我的要求很简单。我正在使用 materialize css 下拉插件。这类似于 bootstrap 下拉菜单。基本上,我写了一个 React 组件来呈现下拉列表的模板。渲染后,在 componentDidMount 函数中,我使用 materialize 插件初始化下拉菜单。
我的组件渲染函数:-
render: function () {
var that = this;
return (
<div>
<a ref="addComponent" className="add-component dropdown-button btn-floating btn-large waves-effect waves-light grey" data-activates='dropdown1'>
<i className="mdi-content-add"></i>
</a>
<ul id='dropdown1' className='dropdown-content'>
{
this.state.items.map(function (item, index) {
return <li key={index} onClick={that.triggerEvent.bind(null, item)}>{item}</li>
})
}
</ul>
</div>
);
}
ComponentDidMount 函数;-
componentDidMount: function () {
var that = this;
var component = $(this.refs.addComponent.getDOMNode());
setTimeout(function () {
component.dropdown({
inDuration: 300,
outDuration: 225,
constrain_width: false, // Does not change width of dropdown to that of the activator
hover: false, // Activate on click
alignment: 'left', // Aligns dropdown to left or right edge (works with constrain_width)
gutter: 0, // Spacing from edge
belowOrigin: false // Displays dropdown below the button
}
);
})
}
我的下拉列表在 getInitialState 函数中初始化:-
getInitialState: function () {
return {
items: ["Item1", "Item2", "Item3"]
}
}
每当我点击按钮时,下拉菜单就会打开。之后,如果我选择任何项目,则不会触发单击事件处理程序。请检查渲染函数中的事件处理程序注册。
<li key={index} onClick={that.triggerEvent.bind(null, item)}>{item}</li>
我在控制台中收到以下错误
Uncaught Error: Invariant Violation: findComponentRoot(..., .0.1.$1): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a when using tables, nesting tags like ,
, or , or using non-SVG elements in an parent. Try inspecting the child nodes of the element with React ID
更多细节请查看jdfiddle http://jsfiddle.net/pashaplus/3u9xug0b/
最佳答案
下拉组件的 materializecss 初始化函数(代码中的 component.dropdown(...)
)修改了 DOM。
您可以通过以下方式观察:
- 在您的
setTimout(...)
中添加显着延迟调用(我加了 30000,所以 30 秒) - 运行 jsfiddle
- 打开您的 Chrome 开发者工具,找到大 (+) 元素,对其周围的源代码进行截图
- 30 秒后您会看到 DOM 发生变化,您可以再截一张图进行比较。
我看到的是你的<ul>
被主体底部的 materializecss 移动(就在关闭 </body>
之前),这意味着它在你的 <div id="container">
之外并且在 react 的范围之外。
所以基本上 react 和 materializecss 不能很好地相互配合。
React 不观察 DOM,它在 virtualDOM 上工作,在某些内容发生变化时计算差异,并对实际 DOM 应用必要的最小变化。因此,React 期望成为唯一对其管理的子树(在 <div id="container">
内)进行突变的人。
至于解决方案,你可以看看这个例如: Using JQuery plugins that transform the DOM in React Components?
关于javascript - 第三方 jquery 下拉插件列表项的 onClick 事件在 react js 中抛出错误。 Uncaught Error : Invariant Violation: findComponentRoot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29398200/