是什么让React库需要preact-compat? [英] What makes a React library require preact-compat?

查看:228
本文介绍了是什么让React库需要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根本不需要它.对于preactchildren属性始终是一个数组.

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 refs 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆