【发布时间】:2018-07-05 21:49:36
【问题描述】:
我有渲染 D3 树的 React 组件。代码sn-p如下。
componentDidMount()
{
var mountNode = ReactDom.findDOMNode(this.tree);
// Render the tree usng d3 after first component mount
if (this.props.treeData)
{
renderTree(this.props.treeData, mountNode, this.props.nodeName);//renderTree is Javascript function
}
}
contextmenu(node)
{
this.setState = {
style_popup: {
top: d3.event.clientY,
left: d3.event.clientX,
position: 'absolute'
},
render_on_click: true
}
}
render()
{
// Render a blank svg node
return (
<div id="tree">
<div id="tree-container" ref={(tree) =>
{
this.tree = tree;
}}>
</div>
{
(this.state.render_on_click) ? <PopUp popup_style={this.state.style_popup}/> : null
}
</div>
);
}
在renderTree() 内部(不是 React 函数)我有以下代码 sn-p:
function renderTree(this.props.treeData, mountNode, this.props.nodeName)
{
//Some code.
.on('click',contextmenu);
}
我知道这是从 Js 调用 contextmenu of React 的错误方式,但我将如何实现呢?我尝试使用 refs
<D3Tree ref={instance => { this.D3tree = instance; }} treeData={this.props.treeData} />
但是 D3Tree 组件是从不同的文件中调用的,这就是我得到的原因
this.D3Tree 未定义。
我应该如何调用作为 React 函数的 contextmenu?
【问题讨论】:
-
renderTree 也是一个 react 组件吗?
-
没有。它是一个javascript函数
-
那么当你调用 contextmenu 时你期望发生什么?相对于 D3Tree,renderTree 在哪里?除非您可以将 contextmenu 绑定到 D3Tree 并通过道具传递,否则我认为该函数不会执行您希望它执行的操作,因为它无法访问您的组件状态
-
contextmenu 是 React 函数设置 React 组件 D3Tree 的状态。现在在 renderTree 函数中,单击时,我希望执行 contextmenu。但我无法调用 contextmenu,因为 renderTree 在 React 组件之外
-
好吧,如果您可以访问组件本身,您可以尝试绑定它。不要将 contextmenu 函数定义为组件上的方法,而是将其定义为单独的函数。然后在你的组件里面你可以说
this.contextmenu = contextmenu.bind(this),在你的renderTree里面你可以说contextmenu = contextmenu.bind(D3Tree)。否则您对this.setState的调用将失败。我不确定这是否可行,但值得一试
标签: javascript reactjs d3.js react-d3