我正在为我的下一个项目考虑 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/