Preact - неразрушающий , когда дело доходит до обновлений DOM. Официальное руководство уже объясняет, как интегрировать внешние 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;
});
Также обратите внимание, что функция render()
в Preact всегда выводит дочерние элементы DOM внутри контейнера. Поэтому, если ваш контейнер содержит DOM, который не был обработан Preact, Preact попытается сопоставить его с элементами, которые вы передаете. - Таким образом, значение неразрушающий .