【问题标题】:Tabulator in React - TypeError: Cannot read property 'tagName' of undefinedReact 中的制表符 - TypeError:无法读取未定义的属性“tagName”
【发布时间】:2020-02-21 03:36:00
【问题描述】:

我收到此错误...

  5440 | this.bindModules();
  5441 | 
> 5442 | if (this.element.tagName === "TABLE") {
       | ^  5443 |   if (this.modExists("htmlTableImport", true)) {
  5444 |     this.modules.htmlTableImport.parseTable();
  5445 |   }

当我尝试使用Tabulator library in a React component

import React, { useState, useEffect } from "react";

import Tabulator from "tabulator-tables";
import "tabulator-tables/dist/css/tabulator.min.css";

function Journal(props) {

    let refTable = React.createRef();

    const [journalItems, setJournalItems] = useState([]);

    useEffect(() => {
        new Tabulator(refTable, {
            data: journalItems,
            reactiveData: true,
            columns: ["a", "b", "c"],
        });
    }, []); 

    return (
        <div>
            <div className="foo" ref={refTable}></div>
        </div >
    )
}

export default Journal;

library example 使用类组件方法,而我想使用函数式方法。

我做错了什么?

【问题讨论】:

  • console.log(this); 可能是很好的第一步。可能是this 的简单案例,并不意味着您认为this 应该是什么。其次,(如果this 案例检查出来)是看看this.element 是什么。是undefined 吗?我敢打赌...
  • this不是没用在功能组件里吗?

标签: javascript reactjs tabulator


【解决方案1】:

我已经解决了这里的问题 - https://codesandbox.io/s/gallant-wright-365ur

createRef 不应该在功能组件中使用。参考——What's the difference between `useRef` and `createRef`?

唯一需要改变的是 -

<div className="foo" ref={el => (refTable = el)} />

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我设法解决了这个问题......

    import React, { useState, useEffect } from "react";
    
    import Tabulator from "tabulator-tables";
    import "tabulator-tables/dist/css/tabulator.min.css";
    
    function Journal(props) {
    
        let refTable = useRef(null);
        let table = useRef(null);
    
        const [journalItems, setJournalItems] = useState([]);
    
        useEffect(() => {
            table.current = new Tabulator(refTable.current, {
                data: journalItems,
                reactiveData: true,
                columns: ["a", "b", "c"],
            });
        }, []); 
    
        return (
            <div>
                <div className="foo" ref={refTable}></div>
            </div >
        )
    }
    
    export default Journal;
    

    这就是问题所在。

    从 React Hook useEffect 内部对 'table' 变量的分配将在每次渲染后丢失。 要随着时间的推移保留该值,请将其存储在 useRef Hook 中,并将可变值保留在 '.current' 属性中。 否则,您可以直接在 useEffect 中移动此变量。 (react-hooks/exhaustive-deps)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2021-09-24
      • 2020-07-10
      • 2019-07-07
      • 2021-03-10
      • 2020-02-10
      • 2021-04-17
      相关资源
      最近更新 更多