繁体   English   中英

从JS函数调用React Component函数

[英]Calling React Component function from JS function

我有渲染D3树的React组件。 代码段如下所示。

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的上下文菜单的错误方式,但是我将如何实现呢? 我尝试使用裁判

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

但是从另一个文件调用了D3Tree组件,这就是我得到的原因

this.D3Tree是未定义的。

我应该如何调用context菜单,这是一个React函数?

在您导出组件的位置,例如

let instance = null;

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

export { MyComponent, instance as myComponentInstance }

之后,您将可以使用来自“文件”的import {myComponentInstance},它将是您的组件的组件,但前提是该组件一次是一个渲染实例,并且仅具有null检查条件。

这也不是一个正确的方法,您的代码将受到支持它的人们的讨厌。

第二种方式-您可以在React组件之外的其他地方编写函数,例如:

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

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

无论如何,这两种方式都是反模式,但您可以实现目标。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM