What makes a React library require preact-compat?

烈酒焚心 提交于 2019-12-11 13:46:48

问题


I have noticed that certain libraries such as classnames are readily available in Preact but others like styled-components require preact-compat.

What makes a React library unsupported natively in preact that it requires the use of preact-compat?


回答1:


Disclaimer: I work on 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.

Some examples:

Children-API:

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:

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"));

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.

findDOMNode:

// React
const element = React.findDOMNode(componentInstance);

// In Preact that's just a property
const element = componentInstance.base;

In our case this even works for function components. Note that in nearly all cases refs are preferred over findDOMNode.

Summary: preact-compat contains mostly shims for third-party libraries expecting full API compatibility with react.



来源:https://stackoverflow.com/questions/53773807/what-makes-a-react-library-require-preact-compat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!