Preact:轻量级替代React的选择

Preact是一个轻量级的JavaScript库,它提供了与React相似的API,但体积更小,性能更优。Preact的核心理念是尽可能地保持与React的兼容性,同时去除不必要的部分,使其成为一个理想的替代品,尤其是在对性能和包大小有严格要求的场景中。本文将详细介绍Preact的基本概念、核心API、性能优势以及如何逐步迁移或开始使用Preact。

Preact简介

Preact由Jason Miller在2016年创建,其设计目标是提供一个与React API一致的框架,但体积更小,运行速度更快。Preact的核心库大小仅为3KB(gzip压缩后),而React的大小约为25KB(gzip压缩后)。尽管体积小,Preact仍然提供了React的大部分功能,包括虚拟DOM、组件化、状态管理和生命周期方法。

Preact基础

安装Preact

首先,确保你已经安装了Node.js和npm。然后,使用npm安装Preact和Preact的DOM适配器:

npm install preact preact-render-to-string
创建第一个Preact应用

创建一个HTML文件,引入Preact和Preact的DOM适配器,编写一个简单的组件:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Preact App</title>
</head>
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/preact/preset.js"></script>
  <script>
    function Hello({ name }) {
      return <h1>Hello, {name}!</h1>;
    }

    preact.render(<Hello name="World" />, document.getElementById('root'));
  </script>
</body>
</html>

Preact组件

函数组件

在Preact中,函数组件是最常用的组件类型,它接收props作为参数,返回一个或多个虚拟DOM节点:

const Greeting = props => <h1>Hello, {props.name}!</h1>;

preact.render(<Greeting name="John Doe" />, document.getElementById('root'));
类组件

类组件继承自preact.Component,可以使用state和生命周期方法:

import { Component } from 'preact';

class Counter extends Component {
  state = { count: 0 };

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={this.increment}>Click me</button>
      </div>
    );
  }
}

preact.render(<Counter />, document.getElementById('root'));

状态与Props

Props

组件可以通过props属性接收外部传递的数据:

const Profile = ({ name, age }) => (
  <div>
    <h1>Name: {name}</h1>
    <p>Age: {age}</p>
  </div>
);

preact.render(<Profile name="Alice" age={25} />, document.getElementById('root'));
State

组件内部的状态通过setState方法更新,这将触发组件重新渲染:

class Counter extends Component {
  state = { count: 0 };

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={this.increment}>Click me</button>
      </div>
    );
  }
}

生命周期方法

Preact的类组件支持生命周期方法,但命名略有不同:

  • componentWillLoad():组件即将加载时调用。
  • componentDidLoad():组件加载完成后调用。
  • componentWillUpdate():组件即将更新时调用。
  • componentDidUpdate():组件更新完成后调用。
  • componentWillUnmount():组件即将卸载时调用。
class LifecycleDemo extends Component {
  state = { count: 0 };

  componentDidMount() {
    console.log('Component did mount');
  }

  componentDidUpdate() {
    console.log('Component did update');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  render() {
    return (
      <div>
        <p>{this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

Hooks

Preact支持React Hooks,包括useStateuseEffect等:

import { useState } from 'preact/hooks';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
};

虚拟DOM与Diff算法

Preact使用虚拟DOM来提高性能,它通过比较前后两次渲染的虚拟DOM树,仅更新有变化的部分,而不是重绘整个页面。

事件处理

Preact的事件处理与React类似,使用驼峰式命名,如onClick:

const Button = ({ onClick }) => <button onClick={onClick}>Click me</button>;

preact.render(<Button onClick={() => alert('Clicked!')} />, document.getElementById('root'));

条件渲染与列表渲染

Preact支持使用三元运算符或逻辑与运算符进行条件渲染,使用map函数进行列表渲染:

const UserList = ({ users }) => (
  <ul>
    {users.map(user => (
      <li key={user.id}>{user.name}</li>
    ))}
  </ul>
);

Context API

Preact的Context API用于跨组件传递数据,避免了props drilling

import { createContext, useContext } from 'preact/hooks';

const ThemeContext = createContext('light');

const ThemeProvider = ({ children }) => (
  <ThemeContext.Provider value="dark">
    {children}
  </ThemeContext.Provider>
);

const App = () => {
  const theme = useContext(ThemeContext);
  return <div>Current theme is {theme}</div>;
};

preact.render(
  <ThemeProvider>
    <App />
  </ThemeProvider>,
  document.getElementById('root')
);

Preact CLI与构建工具

Preact CLI是一个脚手架工具,用于快速创建和配置Preact项目。它提供了与Create React App类似的功能,包括代码拆分、热模块替换和生产构建等功能。

# 创建新项目
npx create-preact-app my-app
cd my-app
npm start
  • 34
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天涯学馆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值