从JS函数调用React组件函数

4

我有一个React组件,用于渲染D3树形结构。以下是代码片段:

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函数),我有以下代码片段:

function renderTree(this.props.treeData, mountNode, this.props.nodeName)
{
//Some code.
.on('click',contextmenu);
}

我知道从JS中调用React的上下文菜单的方法不正确,但是我该如何实现呢?我尝试使用引用(refs)

 <D3Tree ref={instance => { this.D3tree = instance; }}  treeData={this.props.treeData} />

但是D3Tree组件是从另一个文件调用的,这就是我收到

this.D3Tree未定义的原因。

我应该如何调用contextmenu,它是一个React函数?


renderTree也是一个React组件吗? - Robbie Milejczak
不是。这是一个JavaScript函数。 - Akash Sateesh
那么当您调用contextmenu时,您期望发生什么?renderTree与D3Tree有何关系?除非您可以将contextmenu绑定到D3Tree并通过prop传递下去,否则我认为该函数不会实现您想要的功能,因为它无法访问您的组件状态。 - Robbie Milejczak
好的,谢谢。我会尝试一下。但是如果我设置了 this.contextmenu = contextmenu.bind(this),为什么我还要在 renderTree 函数中再次设置 contextmenu = contextmenu.bind(D3Tree) 呢? - Akash Sateesh
这完全取决于范围。我不确定你的设置是什么,所以我无法确切地说。如果contetxmenu绑定在顶级作用域中,则不需要在构造函数中绑定。 - Robbie Milejczak
显示剩余2条评论
1个回答

0
在你的组件导出的地方,例如:
let instance = null;

class MyComponent extends React.Component {
    componentWillMount() {
        instance = this;
    }
    componentWillUnmount() {
        instance = null;
    }
}

export { MyComponent, instance as myComponentInstance }

在你能够使用import { myComponentInstance } from "file"之后,它将成为你组件的一部分,但前提是在同一时间只有一个渲染实例,并且只有在空值检查条件下才能使用。

这也不是一个正确的方式,你的代码会被那些要支持它的人所憎恶。

第二种方法 - 你可以在 React 组件之外编写函数,例如:

const myFunction = (instance, someData) => {
}

class MyComponent extends React.Component {
    myFunction = (someData) => { myFunction(this, someData); }
}

无论哪种方式都是反模式,但您可以实现目标。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接