API 参考

¥API Reference

此页面可快速概览所有导出的函数。

¥This page serves as a quick overview over all exported functions.



组件

¥Component

Component 是一个基类,可以扩展它来创建有状态的 Preact 组件。

¥Component is a base class that can be extended to create stateful Preact components.

组件不是直接实例化,而是由渲染器管理并根据需要创建。

¥Rather than being instantiated directly, Components are managed by the renderer and created as-needed.

import { Component } from 'preact';

class MyComponent extends Component {
  // (see below)
}

Component.render(props, state)

所有组件必须提供 render() 功能。渲染函数传递组件的当前 props 和状态,并且应该返回一个虚拟 DOM 元素(通常是 JSX "element")、一个数组或 null

¥All components must provide a render() function. The render function is passed the component's current props and state, and should return a Virtual DOM Element (typically a JSX "element"), an Array, or null.

import { Component } from 'preact';

class MyComponent extends Component {
    render(props, state) {
        // props is the same as this.props
        // state is the same as this.state

        return <h1>Hello, {props.name}!</h1>;
    }
}

要了解有关组件及其使用方法的更多信息,请查看 组件文档

¥To learn more about components and how they can be used, check out the Components Documentation.

render()

render(virtualDom, containerNode, [replaceNode])

将虚拟 DOM 元素渲染到父 DOM 元素 containerNode 中。不返回任何东西。

¥Render a Virtual DOM Element into a parent DOM element containerNode. Does not return anything.

// DOM tree before render:
// <div id="container"></div>

import { render } from 'preact';

const Foo = () => <div>foo</div>;

render(<Foo />, document.getElementById('container'));

// After render:
// <div id="container">
//  <div>foo</div>
// </div>
Run in REPL

如果提供了可选的 replaceNode 参数,则它必须是 containerNode 的子参数。Preact 将使用其比较算法更新或替换传递的元素,而不是推断从哪里开始渲染。

¥If the optional replaceNode parameter is provided, it must be a child of containerNode. Instead of inferring where to start rendering, Preact will update or replace the passed element using its diffing algorithm.

⚠️ Preact v11 将删除 replaceNode 参数。它引入了太多的边缘情况和错误,需要在 Preact 源代码的其余部分中加以考虑。由于历史原因,我们保留本节,但我们不建议任何人使用第三个 replaceNode 参数。

¥⚠️ The replaceNode-argument will be removed with Preact v11. It introduces too many edge cases and bugs which need to be accounted for in the rest of Preact's source code. We're leaving this section up for historical reasons, but we don't recommend anyone to use the third replaceNode argument.

// DOM tree before render:
// <div id="container">
//   <div>bar</div>
//   <div id="target">foo</div>
// </div>

import { render } from 'preact';

const Foo = () => <div id="target">BAR</div>;

render(
  <Foo />,
  document.getElementById('container'),
  document.getElementById('target')
);

// After render:
// <div id="container">
//   <div>bar</div>
//   <div id="target">BAR</div>
// </div>

第一个参数必须是有效的虚拟 DOM 元素,它表示组件或元素。传递组件时,重要的是让 Preact 进行实例化,而不是直接调用组件,这会以意想不到的方式中断:

¥The first argument must be a valid Virtual DOM Element, which represents either a component or an element. When passing a Component, it's important to let Preact do the instantiation rather than invoking your component directly, which will break in unexpected ways:

const App = () => <div>foo</div>;

// DON'T: Invoking components directly breaks hooks and update ordering:
render(App(), rootElement); // ERROR
render(App, rootElement); // ERROR

// DO: Passing components using h() or JSX allows Preact to render correctly:
render(h(App), rootElement); // success
render(<App />, rootElement); // success

hydrate()

如果你已经将应用预渲染或服务器端渲染为 HTML,则在浏览器中加载时,Preact 可以绕过大多数渲染工作。这可以通过从 render() 切换到 hydrate() 来启用,这会跳过大多数差异,同时仍然附加事件监听器并设置组件树。这仅在与预渲染或 服务器端渲染 结合使用时才有效。

¥If you've already pre-rendered or server-side-rendered your application to HTML, Preact can bypass most rendering work when loading in the browser. This can be enabled by switching from render() to hydrate(), which skips most diffing while still attaching event listeners and setting up your component tree. This works only when used in conjunction with pre-rendering or Server-Side Rendering.

import { hydrate } from 'preact';

const Foo = () => <div>foo</div>;
hydrate(<Foo />, document.getElementById('container'));
Run in REPL

h() / createElement()

h(type, props, ...children)

返回具有给定 props 的虚拟 DOM 元素。虚拟 DOM 元素是应用 UI 层次结构中节点的轻量级描述,本质上是 { type, props } 形式的对象。

¥Returns a Virtual DOM Element with the given props. Virtual DOM Elements are lightweight descriptions of a node in your application's UI hierarchy, essentially an object of the form { type, props }.

typeprops 之后,所有剩余参数都将收集到 children 属性中。子级可能属于以下任何一种:

¥After type and props, any remaining parameters are collected into a children property. Children may be any of the following:

  • 标量值(字符串、数字、布尔值、null、未定义等)

    ¥Scalar values (string, number, boolean, null, undefined, etc)

  • 嵌套虚拟 DOM 元素

    ¥Nested Virtual DOM Elements

  • 上述无限嵌套数组

    ¥Infinitely nested Arrays of the above

import { h } from 'preact';

h('div', { id: 'foo' }, 'Hello!');
// <div id="foo">Hello!</div>

h('div', { id: 'foo' }, 'Hello', null, ['Preact!']);
// <div id="foo">Hello Preact!</div>

h(
    'div',
    { id: 'foo' },
    h('span', null, 'Hello!')
);
// <div id="foo"><span>Hello!</span></div>

toChildArray

此辅助函数将 props.children 值转换为展平数组,无论其结构或嵌套如何。如果 props.children 已经是一个数组,则返回一个副本。当 props.children 可能不是数组时,此函数非常有用,这种情况可能发生在 JSX 中静态和动态表达式的某些组合中。

¥This helper function converts a props.children value to a flattened Array regardless of its structure or nesting. If props.children is already an array, a copy is returned. This function is useful in cases where props.children may not be an array, which can happen with certain combinations of static and dynamic expressions in JSX.

对于具有单个子元素的虚拟 DOM 元素,props.children 是对子元素的引用。当有多个子级时,props.children 始终是一个数组。toChildArray 助手提供了一种一致处理所有情况的方法。

¥For Virtual DOM Elements with a single child, props.children is a reference to the child. When there are multiple children, props.children is always an Array. The toChildArray helper provides a way to consistently handle all cases.

import { toChildArray } from 'preact';

function Foo(props) {
  const count = toChildArray(props.children).length;
  return <div>I have {count} children</div>;
}

// props.children is "bar"
render(
  <Foo>bar</Foo>,
  container
);

// props.children is [<p>A</p>, <p>B</p>]
render(
  <Foo>
    <p>A</p>
    <p>B</p>
  </Foo>,
  container
);

cloneElement

cloneElement(virtualElement, props, ...children)

此函数允许你创建虚拟 DOM 元素的浅表副本。它通常用于添加或覆盖元素的 props

¥This function allows you to create a shallow copy of a Virtual DOM Element. It's generally used to add or overwrite props of an element:

function Linkout(props) {
  // add target="_blank" to the link:
  return cloneElement(props.children, { target: '_blank' });
}
render(<Linkout><a href="/">home</a></Linkout>);
// <a href="/" target="_blank">home</a>

createContext

请参阅 上下文文档 中的部分。

¥See the section in the Context documentation.

createRef

提供一种在渲染后引用元素或组件的方法。

¥Provides a way to reference an element or component once it has been rendered.

有关详细信息,请参阅 参考文档

¥See the References documentation for more details.

Fragment

一种特殊类型的组件,可以有子组件,但不会渲染为 DOM 元素。片段可以返回多个同级子级,而无需将它们封装在 DOM 容器中:

¥A special kind of component that can have children, but is not rendered as a DOM element. Fragments make it possible to return multiple sibling children without needing to wrap them in a DOM container:

import { Fragment, render } from 'preact';

render(
  <Fragment>
    <div>A</div>
    <div>B</div>
    <div>C</div>
  </Fragment>,
  document.getElementById('container')
);
// Renders:
// <div id="container>
//   <div>A</div>
//   <div>B</div>
//   <div>C</div>
// </div>
Run in REPL
Preact 中文网 - 粤ICP备13048890号