dom - 使用 Preactjs 时可以直接操作 DOM 吗?

标签 dom dom-manipulation preact

我正在为我的下一个项目考虑 Preact。

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

Preact 会与另一个操作 DOM 的库(例如 SVGjs)发生冲突吗?

最佳答案

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" />;
  }
}

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

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

关于dom - 使用 Preactjs 时可以直接操作 DOM 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60888473/

相关文章:

Javascript INDEX_SIZE_ERR : DOM Exception 1 Error for ranges

javascript - 将持久事件类附加到导航栏范围内的导航元素(AngularJS)

javascript - preactjs 看到 [Object object] 而不是链接

webpack - 样式化组件添加组件名称作为类名称

jquery - 根据屏幕尺寸重新排列 DOM 的最佳方法

javascript - Preact 粒子

c# - 强制将 XML 字符实体放入 XmlDocument 中

javascript - 如何访问 Electron 中的DOM元素?

jquery - 幻灯片 DOM 操作

javascript - 将图像设置为同级元素的背景