【前端资讯】重磅升级!Preact X 发布!
Preact X 是从 Preact 8.x 向前迈出的一大步(这是向 iPhone 致敬?)。开发团队重新斟酌了代码的每个细节,并在此过程中添加了许多重要的新功能,同时也增强了兼容性,以便支持更多的第三方库。
因为新功能与 React 一致,所以这里只是罗列一下,新功能的详情可以阅读原文或者搜索 React 相应的功能介绍。
Fragments
function Foo() {
return (
<>
<div>A</div>
<div>B</div>
</>
)
}
componentDidCatch
class Catcher extends Component {
state = { errored: false }
componentDidCatch(error) {
this.setState({ errored: true });
}
render(props, state) {
if (state.errored) {
return <p>Something went badly wrong</p>;
}
return props.children;
}
}
Hooks
function Counter() {
const [value, setValue] = useState(0);
const increment = useCallback(() => setValue(value + 1), [value]);
return (
<div>
Counter: {value}
<button onClick={increment}>Increment</button>
</div>
);
}
createContext
const Theme = createContext('light');
function ThemedButton(props) {
return (
<Theme.Consumer>
{theme => <div>Active theme: {theme}</div>}
</Theme.Consumer>
);
}
function App() {
return (
<Theme.Provider value="dark">
<SomeComponent>
<ThemedButton />
</SomeComponent>
</Theme.Provider>
);
}
CSS Custom Properties
function Foo(props) {
return <div> style={{ '--theme-color': 'blue' }}>{props.children}</div>;
}
preact-compat 合并至 Preact
// Preact 8.x
import React from "preact-compat";
// Preact X
import React from "preact/compat";