亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Quick Start
Create and render components
Use Signals to track changing values
Responsive primitives
createEffect
createMemo
Lifecycle method
storage
Control flow
Demo project
Home Web Front-end CSS Tutorial Introduction to the Solid JavaScript Library

Introduction to the Solid JavaScript Library

Mar 20, 2025 am 09:42 AM

SolidJS: A high-performance responsive JavaScript UI library

Introduction to the Solid JavaScript Library

Solid is a responsive JavaScript library for creating user interfaces, which does not require virtual DOM. It compiles the template into a real DOM node and wraps the updates in a fine-grained reaction, so when the state is updated, only the relevant code will run.

This method allows the compiler to optimize initial rendering and runtime updates. This focus on performance makes it one of the most acclaimed JavaScript frameworks.

I was curious about this and wanted to give it a try, so I spent some time creating a small to-do application to explore how this framework handles rendering components, updating state, setting up storage, and more.

If you can't wait to see the final code and results, check out the final demo: [The final demo link should be inserted here, not provided in the original text]

Quick Start

Like most frameworks, we can start by installing the npm package. To use the framework with JSX, run:

 npm install solid-js babel-preset-solid

Then we need to add babel-preset-solid to our Babel, webpack or Rollup configuration file:

 "presets": ["solid"]

Or, if you want to set up a small application, you can also use one of their templates:

 # Create a small application from Solid template npx degit solidjs/templates/js my-app

# Change to the created project directory cd my-app

# Install dependencies npm i # or yarn or pnpm

# Start the development server npm run dev

TypeScript is supported, if you want to start a TypeScript project, change the first command to npx degit solidjs/templates/ts my-app .

Create and render components

The syntax of the rendering component is similar to React.js, so it may look familiar:

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

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

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

We need to import the render function first, then create a div with text and prop, and call render, passing in the component and container elements.

This code is then compiled into a real DOM expression. For example, the above code example, once compiled by Solid, looks like this:

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

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

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

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

Solid Playground is very cool, it shows that Solid has different rendering methods, including client, server and client with hydration.

Use Signals to track changing values

Solid uses a hook called createSignal , which returns two functions: a getter and a setter. This may look a little weird if you're used to using frameworks like React.js. You usually expect the first element to be the value itself; however, in Solid we need to explicitly call getters to intercept where the read value is located in order to keep track of its changes.

For example, if we are writing the following code:

 const [todos, addTodos] = createSignal([]);

Recording todos does not return a value, but a function. If we want to use the value, we need to call the function, such as todos() .

For a small to-do list, this will be:

 import { createSignal } from "solid-js";

const TodoList = () => {
  let input;
  const [todos, addTodos] = createSignal([]);

  const addTodo = value => {
    return addTodos([...todos(), value]);
  };

  Return (
    <h1>To do list:</h1>
    <input type="text" ref="{el"> input = el} />
    <button onclick="{()"> addTodo(input.value)}>Add item</button>
    
    {todos().map(item => (
  • {item}
  • ))}
); };

The above code example will display a text field, and after clicking the "Add Project" button, the todos will be updated with the new project and it will be displayed in the list.

This may look very similar to using useState , so what is the difference between using getter? Consider the following code example:

 console.log("Create Signals");
const [firstName, setFirstName] = createSignal("Whitney");
const [lastName, setLastName] = createSignal("Houston");
const [displayFullName, setDisplayFullName] = createSignal(true);

const displayName = createMemo(() => {
  if (!displayFullName()) return firstName();
  return `${firstName()} ${lastName()}`;
});

createEffect(() => console.log("My name is", displayName()));

console.log("Set showFullName: false ");
setDisplayFullName(false);

console.log("Change lastName");
setLastName("Boop");

console.log("Set showFullName: true ");
setDisplayFullName(true);

Running the above code will get:

 <code>Create Signals My name is Whitney Houston Set showFullName: false My name is Whitney Change lastName Set showFullName: true My name is Whitney Boop</code>

The main point to note is that after setting a new lastName, "My name is..." is not recorded. This is because nothing is listening for changes to lastName() at this point. The new value of displayFullName() is set only when the value of displayName() changes, which is why when setShowFullName is set to true, we can see that the new lastName is displayed.

This provides us with a safer way to track updates of values.

Responsive primitives

In the last code example, I introduced createSignal , and there are some other primitives: createEffect and createMemo .

createEffect

createEffect tracks dependencies and runs after each rendering of the dependency changes.

 // Don't forget to import it first using 'import { createEffect } from "solid-js";' const [count, setCount] = createSignal(0);

createEffect(() => {
  console.log("Count is at", count());
});

Every time the value of count() changes, "Count is at..." will be recorded

createMemo

createMemo creates a read-only signal that recalculates its value whenever the dependencies of the executed code are updated. It can be used when you want to cache some values ??and access them without reevaluating them (until the dependency changes).

For example, if we want to display a counter 100 times and update the value when the button is clicked, using createMemo will allow recalculation to occur only once per click:

 function Counter() {
  const [count, setCount] = createSignal(0);
  // It will be called 100 times without creatingMemo wrapping counter // const counter = () => {
  // return count();
  // }

  // Wrapping counter with createMemo, only called once per update // Don't forget to use 'import { createMemo } from "solid-js";' to import it const counter = createMemo(() => count());

  Return (
    <div>
      <button onclick="{()"> setCount(count() 1)}>Count: {count()}</button>
      <div>1. {counter()}</div>
      <div>2. {counter()}</div>
      <div>3. {counter()}</div>
      <div>4. {counter()}</div>
    </div>
  );
}

Lifecycle method

Solid exposes several lifecycle methods, such as onMount , onCleanup , and onError . If we want some code to run after initial rendering, we need to use onMount :

 // Don't forget to import it first using 'import { onMount } from "solid-js";' onMount(() => {
  console.log("I mounted!");
});

onCleanup is similar to componentDidUnmount in React — it runs when responsive scope recalculation.

onError is executed when an error occurs in the most recent subscope. For example, when the data acquisition fails, we can use it.

storage

To create a store for data, Solid exposes createStore , whose return value is a read-only proxy object and a setter function.

For example, if we change our to-do example to use storage instead of state, it would look like this:

 const [todos, addTodos] = createStore({ list: [] });

createEffect(() => {
  console.log(todos.list);
});

onMount(() => {
  addTodos('list', (list) => [...list, { item: "a new todo item", completed: false }]);
});

The above code example will first record a proxy object with an empty array, and then record a proxy object with an array containing the object {item: "a new todo item", completed: false} .

It should be noted that if its properties are not accessed, the top-level state object cannot be tracked - that is why we log todos.list instead of todos .

If we only record todos in createEffect , we will see the initial value of the list, but we will not see the updated value in onMount .

To change the values ??in the store, we can update them using the settings function defined when using createStore . For example, if we want to update the to-do list item to "completed", we can update the storage this way:

 const [todos, setTodos] = createStore({
  list: [{ item: "new item", completed: false }]
});

const markAsComplete = text => {
  setTodos(
    "list",
    (i) => i.item === text,
    "completed",
    (c) => !c
  );
};

Return (
  <button onclick="{()"> markAsComplete("new item")}>Mark as complete</button>
);

Control flow

To avoid wasting all DOM nodes are recreated every time they are updated when using methods like .map() , Solid allows us to use the template assistant.

Some of these are available, such as For for looping through projects, Show for conditionally showing and hiding elements, Switch and Match for displaying elements that match specific conditions, and so on!

Here are some examples showing how to use them:

<for each="{todos.list}" fallback="{<div"> Loading... }>
  {(item) =><div> {item}</div> }
</for>
<show when="{todos.list[0]?.completed}" fallback="{<div"> Loading... }>
  <div>1st item completed</div>
</show>
<switch fallback="{<div"> No items }>
  <match when="{todos.list[0]?.completed}"><completedlist></completedlist></match>
  <match when="{!todos.list[0]?.completed}"><todolist></todolist></match>
</switch>

Demo project

Here is a quick introduction to the basics of Solid. If you want to try it, I created a starter project that you can automatically deploy to Netlify and clone to your GitHub by clicking the button below!

[The button that is deployed to Netlify should be inserted here, not provided in the original text] This project includes the default settings for the Solid project, as well as an example to-do application for the basic concepts I mentioned in this post to help you get started!

This framework is much more than what I've covered here, so feel free to check out the documentation for more information!

The above is the detailed content of Introduction to the Solid JavaScript Library. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
CSS tutorial for creating loading spinners and animations CSS tutorial for creating loading spinners and animations Jul 07, 2025 am 12:07 AM

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

Addressing CSS Browser Compatibility issues and prefixes Addressing CSS Browser Compatibility issues and prefixes Jul 07, 2025 am 01:44 AM

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

What is the difference between display: inline, display: block, and display: inline-block? What is the difference between display: inline, display: block, and display: inline-block? Jul 11, 2025 am 03:25 AM

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Creating custom shapes with css clip-path Creating custom shapes with css clip-path Jul 09, 2025 am 01:29 AM

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Styling visited links differently with CSS Styling visited links differently with CSS Jul 11, 2025 am 03:26 AM

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

What is the CSS Painting API? What is the CSS Painting API? Jul 04, 2025 am 02:16 AM

TheCSSPaintingAPIenablesdynamicimagegenerationinCSSusingJavaScript.1.DeveloperscreateaPaintWorkletclasswithapaint()method.2.TheyregisteritviaregisterPaint().3.ThecustompaintfunctionisthenusedinCSSpropertieslikebackground-image.Thisallowsfordynamicvis

How to create responsive images using CSS? How to create responsive images using CSS? Jul 15, 2025 am 01:10 AM

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

What are common CSS browser inconsistencies? What are common CSS browser inconsistencies? Jul 26, 2025 am 07:04 AM

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

See all articles