Solid – A declarative JavaScript library for building user interfaces

栏目: IT技术 · 发布时间: 3年前

内容简介:Solid is a declarative Javascript library for creating user interfaces. It does not use a Virtual DOM. Instead it opts to compile its templates down to real DOM nodes and wrap updates in fine grained reactions. This way when your state updates only the cod

Solid – A declarative JavaScript library for building user interfaces

Solid is a declarative Javascript library for creating user interfaces. It does not use a Virtual DOM. Instead it opts to compile its templates down to real DOM nodes and wrap updates in fine grained reactions. This way when your state updates only the code that depends on it runs.

Key Features

  • Real DOM with fine-grained updates ( No Virtual DOM! No Dirty Checking Digest Loop! ).
  • Declarative data
    • Simple composable primitives without the hidden rules.
    • Function Components with no need for lifecycle methods or specialized configuration objects.
    • Render once mental model.
  • Fast! Almost indistinguishable performance vs optimized painfully imperative vanilla DOM code. See Solid on JS Framework Benchmark .
  • Small! Completely tree-shakeable Solid's compiler will only include parts of the library you use.
  • Supports modern features like JSX, Fragments, Context, Portals, Suspense, SSR, Error Boundaries and Asynchronous Rendering.
  • Built on TypeScript.
  • Webcomponent friendly
    • Context API that spans Custom Elements
    • Implicit event delegation with Shadow DOM Retargeting
    • Shadow DOM Portals
  • Transparent debugging: a <div> is just a div.

The Gist

import { render } from "solid-js/dom";

const HelloMessage = props => <div>Hello {props.name}</div>;

render(
  () => <HelloMessage name="Taylor" />,
  document.getElementById("hello-example")
);

A Simple Component is just a function that accepts properties. Solid uses a render function to create the reactive mount point of your application.

The JSX is then compiled down to efficient real DOM expressions:

import { render, template, insert, createComponent } from "solid-js/dom";

const _tmpl$ = template(`<div>Hello </div>`);

const HelloMessage = props => {
  const _el$ = _tmpl$.cloneNode(true);
  insert(_el$, () => props.name, null);
  return _el$;
};

render(
  () => createComponent(HelloMessage, { name: "Taylor" }),
  document.getElementById("hello-example")
);

That _el$ is a real div element and props.name , Taylor in this case, is appended to it's child nodes. Notice that props.name is wrapped in a function. That is because that is the only part of this component that will ever execute again. Even if a name is updated from the outside only that one expression will be re-evaluated. The compiler optimizes initial render and the runtime optimizes updates. It's the best of both worlds.

Installation

You can get started with a simple app with the CLI with by running:

> npm init solid app my-app

Use app-ts for a TypeScript starter.

npm init solid <project-type> <project-name> is available with npm 6+.

Or you can install the dependencies in your own project. To use Solid with JSX (recommended) run:

> npm install solid-js babel-preset-solid

Solid Rendering

Solid's rendering is done by the DOM Expressions library. This library provides a generic optimized runtime for fine grained libraries like Solid with the opportunity to use a number of different Rendering APIs. The best option is to use JSX pre-compilation with Babel Plugin JSX DOM Expressions to give the smallest code size, cleanest syntax, and most performant code. The compiler converts JSX to native DOM element instructions and wraps dynamic expressions in reactive computations.

The easiest way to get setup is add babel-preset-solid to your .babelrc, or babel config for webpack, or rollup:

"presets": ["solid"]

Remember even though the syntax is almost identical, there are significant differences between how Solid's JSX works and a library like React. Refer to JSX Rendering for more information.

Alternatively in non-compiled environments you can use Tagged Template Literals Lit DOM Expressions or even HyperScript with Hyper DOM Expressions .

For convenience Solid exports interfaces to runtimes for these as:

import h from "solid-js/h";
import html from "solid-js/html";

Remember you still need to install the library separately for these to work.

Solid State

Solid's data management is built off a set of flexible reactive primitives. Similar to React Hooks except instead of whitelisting change for an owning Component they independentally are soley responsible for all the updates.

Solid's State primitive is arguably its most powerful and distinctive one. Through the use of proxies and explicit setters it gives the control of an immutable interface and the performance of a mutable one. The setters support a variety of forms, but to get started set and update state with an object.

import { createState, onCleanup } from "solid-js";

const CountingComponent = () => {
  const [state, setState] = createState({ counter: 0 });

  const interval = setInterval(
    () => setState({ counter: state.counter + 1 }),
    1000
  );

  onCleanup(() => clearInterval(interval));

  return <div>{state.counter}</div>;
};

Where the magic happens is with computations(effects and memos) which automatically track dependencies.

const [state, setState] = createState({ user: { firstName: "Jake", lastName: "Smith" }})

createEffect(() =>
  setState({
    displayName: `${state.user.firstName} ${state.user.lastName}`
  })
);

console.log(state.displayName); // Jake Smith
setState('user', {firstName: "Jacob" });
console.log(state.displayName); // Jacob Smith

Whenever any dependency changes the State value will update immediately. Each setState statement will notify subscribers synchronously with all changes applied. This means you can depend on the value being set on the next line.

Solid State also exposes a reconcile method used with setState that does deep diffing to allow for automatic efficient interopt with immutable store technologies like Redux, Apollo(GraphQL), or RxJS.

const unsubscribe = store.subscribe(({ todos }) => (
  setState('todos', reconcile(todos)));
);
onCleanup(() => unsubscribe());

Read these two introductory articles by @aftzl :

Understanding Solid: Reactivity Basics

Understanding Solid: JSX

And check out the Documentation, Examples, and Articles below to get more familiar with Solid.

Documentation

Examples

Related Projects

Latest Articles

Status

Solid is mostly feature complete for its v1.0.0 release. The next releases will be mostly bug fixes API tweaks on the road to stability.


以上所述就是小编给大家介绍的《Solid – A declarative JavaScript library for building user interfaces》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

增长黑客

增长黑客

范冰 / 电子工业出版社 / 2015-7-1 / CNY 59.00

“增长黑客”这一概念近年来兴起于美国互联网创业圈,最早是由互联网创业者Sean Ellis提出。增长黑客是介于技术和市场之间的新型团队角色,主要依靠技术和数据的力量来达成各种营销目标,而非传统意义上靠砸钱来获取用户的市场推广角色。他们能从单线思维者时常忽略的角度和难以企及的高度通盘考虑影响产品发展的因素,提出基于产品本身的改造和开发策略,以切实的依据、低廉的成本、可控的风险来达成用户增长、活跃度上......一起来看看 《增长黑客》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

MD5 加密
MD5 加密

MD5 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器