您可以在使用Preactjs时直接操作DOM吗?

时间:2020-03-27 14:53:38

标签: dom dom-manipulation preact

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

由于它没有虚拟DOM,所以我想知道它是否像React一样,希望您让框架操作DOM而不是直接自己操作。

Preact颠簸头是否会带有另一个可操纵DOM的库(例如SVGjs)?

1 个答案:

答案 0 :(得分:1)

关于DOM更新,

Preact是非破坏性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" />;
  }
}

如果使用钩子,则使用memo中的preact/compat函数:

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会尝试将其与您传递的元素进行比较。 -因此是非破坏性的意思。