【问题标题】:React-Flow: Can you pass props to a custom node in React-Flow?React-Flow:你可以将 props 传递给 React-Flow 中的自定义节点吗?
【发布时间】:2022-08-16 19:31:31
【问题描述】:

我正在使用 React-Flow 来可视化 React 中组件的树状层次结构。每当你在 React-Flow 中创建一个自定义节点时,你都会像这样在树中使用它:

  <ReactFlow
      onLoad={onLoadTree}
      elements={nodesAndEdges}
      nodeTypes={{ reactComponent: ComponentNode }}

这使得无法通过道具。假设我想传递一些东西,那么如果语法类似于reactComponent: &lt;ComponentNode myProps={myProps} /&gt;,我就可以做到这一点。以前有没有人使用过这项技术并且知道是否有可能将道具传递给自定义节点? :) 谢谢!

    标签: javascript reactjs react-flow


    【解决方案1】:

    创建新节点时,您可以在 data 属性部分传递所需的任何数据:

    const newNode = {
      ...nodeProps,
      data: {
        myCustomProps: "test",
      },
    }
    

    【讨论】:

    • 感谢您的评论!是的,你可以做到。 :D
    • 那你如何访问道具呢?
    • @JUB0T 你能在下面查看我的答案吗?
    【解决方案2】:

    看来您可以在节点的data 属性中传递道具。

    【讨论】:

      【解决方案3】:

      你可以这样做

      const YourComponent = () => {
        const componentNode = { reactComponent: (props) => <ComponentNode myProp="myProps" {...props} />};
      
        return (
          <ReactFlow
            onLoad={onLoadTree}
            elements={nodesAndEdges}
            nodeTypes={componentNode}
          />
        );
      };
      

      在这里通过 props,你可以得到预定义的 props,比如 data、id 等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-23
        • 2023-03-08
        • 2017-04-24
        • 2019-08-11
        • 1970-01-01
        • 2021-03-17
        • 2021-09-17
        相关资源
        最近更新 更多