Solid – A declarative JavaScript library for building user interfaces

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

内容简介: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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

降维攻击

降维攻击

高德 / 世界图书出版公司 / 2016-3-31 / 39.80元

本书优势: 第一,降维攻击是一个刚开始流行的商业概念,未来随着电影《三体》的上映,这个概念会更加流行,会成为一个全社会的讨论热点。推出这本书,正好借势营销,是一个热点窗口,同时这个概念的商业价值,又符合了时下市场的需求。 第二,这本书的案例和分析,立足于本土,因为降维攻击的思维,很好地表现了国内许多互联网企业崛起的过程,百度,阿里、腾讯、京东等电商的崛起历程都充满了降维的智慧,对于目前......一起来看看 《降维攻击》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

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

Markdown 在线编辑器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具