vlambda博客
学习文章列表

【前端资讯】重磅升级!Preact X 发布!



Preact X 是从 Preact 8.x 向前迈出的一大步(这是向 iPhone 致敬?)。开发团队重新斟酌了代码的每个细节,并在此过程中添加了许多重要的新功能,同时也增强了兼容性,以便支持更多的第三方库。


因为新功能与 React 一致,所以这里只是罗列一下,新功能的详情可以阅读原文或者搜索 React 相应的功能介绍。


Fragments

 
   
   
 
  1. function Foo() {

  2. return (

  3. <>

  4. <div>A</div>

  5. <div>B</div>

  6. </>

  7. )

  8. }


componentDidCatch

 
   
   
 
  1. class Catcher extends Component {

  2. state = { errored: false }


  3. componentDidCatch(error) {

  4. this.setState({ errored: true });

  5. }


  6. render(props, state) {

  7. if (state.errored) {

  8. return <p>Something went badly wrong</p>;

  9. }

  10. return props.children;

  11. }

  12. }


Hooks

 
   
   
 
  1. function Counter() {

  2. const [value, setValue] = useState(0);

  3. const increment = useCallback(() => setValue(value + 1), [value]);


  4. return (

  5. <div>

  6. Counter: {value}

  7. <button onClick={increment}>Increment</button>

  8. </div>

  9. );

  10. }


createContext

 
   
   
 
  1. const Theme = createContext('light');


  2. function ThemedButton(props) {

  3. return (

  4. <Theme.Consumer>

  5. {theme => <div>Active theme: {theme}</div>}

  6. </Theme.Consumer>

  7. );

  8. }


  9. function App() {

  10. return (

  11. <Theme.Provider value="dark">

  12. <SomeComponent>

  13. <ThemedButton />

  14. </SomeComponent>

  15. </Theme.Provider>

  16. );

  17. }


CSS Custom Properties

 
   
   
 
  1. function Foo(props) {

  2. return <div> style={{ '--theme-color': 'blue' }}>{props.children}</div>;

  3. }


preact-compat 合并至 Preact

 
   
   
 
  1. // Preact 8.x

  2. import React from "preact-compat";


  3. // Preact X

  4. import React from "preact/compat";