是什么让React库需要preact-compat? [英] What makes a React library require preact-compat?
问题描述
我注意到某些库(例如classnames
)在Preact中很容易获得,而其他库(例如styled-components
则需要preact-compat
.)
I have noticed that certain libraries such as classnames
are readily available in Preact but others like styled-components
require preact-compat
.
是什么使React库在本来就不需要使用preact-compat的情况下本身不受支持的?
What makes a React library unsupported natively in preact that it requires the use of preact-compat?
推荐答案
免责声明:我从事精确的工作.
Disclaimer: I work on preact.
react
中不需要几个API,而preact
则不需要.但是,由于已经为这些API开发了现有的第三方库,因此我们发布了preact-compat
,该库在preact
之上重新实现了它们.
There are several APIs in react
that are not needed for preact
. But because existing third-party libraries have been developed for those APIs we published preact-compat
which re-implements them on top of preact
.
一些例子:
此API特别有趣,因为preact
根本不需要它.对于preact
,children
属性始终是一个数组.
This API is in particular interesting because it isn't needed at all for preact
. With preact
the children
property is always an array.
// React
Children.forEach(props.children, child => ...);
Children.map(props.children, child => ...);
Children.count(props.children);
// Preact
props.children.forEach(child => ...);
props.children.map(child => ...);
props.children.length;
unmountComponentAtNode
:
这是preact
不需要的另一个API,因为我们可以通过渲染null
来简单地卸载任何树:
unmountComponentAtNode
:
This is another API that is not needed for preact
, because we can simply unmount any tree by rendering null
:
import { render } from "preact";
import App from "./app";
// Render App into dom
render(<App />, document.getElementById("root"));
// Unmount tree
render(null, document.getElementById("root"));
如果要删除子树而不是根节点,可以通过从组件返回null
来实现.基本上null
总是被视为 empty 值.
If you want to drop a subtree instead of the root node you can do that via returning null
from a component. Basically null
is always treated as an empty value.
// React
const element = React.findDOMNode(componentInstance);
// In Preact that's just a property
const element = componentInstance.base;
在我们的例子中,这甚至适用于功能组件.请注意,在几乎所有情况下,ref
都比findDOMNode
更为可取.
In our case this even works for function components. Note that in nearly all cases ref
s are preferred over findDOMNode
.
摘要::preact-compat
主要包含希望与react
完全兼容的第三方库的填充程序.
Summary: preact-compat
contains mostly shims for third-party libraries expecting full API compatibility with react
.
这篇关于是什么让React库需要preact-compat?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!