【问题标题】:Calling React Component function from JS function从 JS 函数调用 React 组件函数
【发布时间】: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


【解决方案1】:

在您导出组件的地方, 喜欢

let instance = null;

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

export { MyComponent, instance as myComponentInstance }

之后你就可以使用 import { myComponentInstance } from "file" 它将是您的组件的 this,但前提是它是一次渲染的一个实例,并且仅具有空检查条件。

这也不是正确的方法,你的代码会被支持它的人讨厌。

第二种方式 - 你可以在 React 组件之外的其他地方编写函数 喜欢:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-08-14
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多