【问题标题】:Can you manipulate the DOM directly while using Preactjs?使用 Preactjs 时可以直接操作 DOM 吗?
【发布时间】:2020-03-27 14:53:38
【问题描述】:

我正在为我的下一个项目研究 Preact。

由于它没有虚拟 DOM,我想知道它是否像 React 一样,更喜欢让框架操作 DOM 而不是自己直接操作。

Preact 是否会与另一个操纵 DOM 的库(例如 SVGjs)碰撞?

【问题讨论】:

    标签: dom dom-manipulation preact


    【解决方案1】:

    Preact 在 DOM 更新方面是非破坏性的official guide 已经解释了如何将外部 DOM 操作集成到 preact 组件中:

    如果使用基于类的组件:

    import { h, Component } from 'preact';
    
    class Example extends Component {
    
      shouldComponentUpdate() {
        // IMPORTANT: do not re-render via diff:
        return false;
      }
    
      componentWillReceiveProps(nextProps) {
        // you can do something with incoming props here if you need
      }
    
      componentDidMount() {
        // now mounted, can freely modify the DOM:
        const thing = document.createElement('maybe-a-custom-element');
        this.base.appendChild(thing);
      }
    
      componentWillUnmount() {
        // component is about to be removed from the DOM, perform any cleanup.
      }
    
      render() {
        return <div class="example" />;
      }
    }
    

    如果使用钩子,则使用来自preact/compatmemo 函数:

    import { h } from 'preact';
    import { useEffect } from 'preact/hooks';
    import { memo } from 'preact/compat';
    
    function Example(props) {
    
      const [node, setNode] = setState(null);
    
      useEffect(() => {
        const elm = document.createElement('maybe-a-custom-element');
    
        setNode(elm);
    
        // Now do anything with the elm.
        // Append to body or <div class="example"></div>
    
      }, []);
    
      return <div class="example" />;
    }
    
    // Usage with default comparison function
    const Memoed = memo(Example);
    
    // Usage with custom comparison function
    const Memoed2 = memo(Example, (prevProps, nextProps) => {
      // Only re-render when `name' changes
      return prevProps.name === nextProps.name;
    });
    

    另外,请注意 Preact 的 render() 函数总是区分容器内的 DOM 子项。因此,如果您的容器包含 Preact 未渲染的 DOM,Preact 将尝试将其与您传递给它的元素进行比较。 - 因此意思是非破坏性

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 2018-07-21
      • 2018-04-21
      • 1970-01-01
      • 2020-09-15
      • 2010-10-21
      • 2020-04-26
      • 2012-05-17
      • 2020-04-24
      相关资源
      最近更新 更多