Heim > Web-Frontend > js-Tutorial > Hauptteil

React Basics

DDD
Freigeben: 2024-09-19 06:19:37
Original
908 Leute haben es durchsucht

Here’s an explanation of key React terminology with examples:

1. Component

A component is the building block of a React application. It’s a JavaScript function or class that returns a portion of the UI (User Interface).

Functional Component (common in modern React):

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}
Nach dem Login kopieren

Class Component (older style):

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}
Nach dem Login kopieren

2. JSX (JavaScript XML)

JSX allows you to write HTML-like syntax inside JavaScript. It’s syntactic sugar for React.createElement().

Example:

const element = <h1>Hello, world!</h1>;

JSX is compiled to:

const element = React.createElement('h1', null, 'Hello, world!');
Nach dem Login kopieren

3. Props (Properties)

Props are how data is passed from one component to another. They are read-only and allow components to be dynamic.

Example:

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

<Greeting name="Alice" />
Nach dem Login kopieren

4. State

State is a JavaScript object that holds dynamic data and affects the rendered output of a component. It can be updated with setState (class components) or the useState hook (functional components).

Example with useState in functional components:

import { useState } from 'react';

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

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

5. Hooks

Hooks are functions that let you use state and other React features in functional components.

useState: Manages state in functional components.
useEffect: Runs side effects in functional components.

Example of useEffect:

import { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return <h1>{seconds} seconds have passed.</h1>;
}
Nach dem Login kopieren

6. Virtual DOM

The Virtual DOM is a lightweight copy of the real DOM. React uses this to track changes and update the UI efficiently by only re-rendering the parts of the DOM that changed, rather than the entire page.

7. Event Handling

React uses camelCase for event handlers instead of lowercase, and you pass functions as the event handler instead of strings.

Example:

function ActionButton() {
  function handleClick() {
    alert('Button clicked!');
  }

  return <button onClick={handleClick}>Click me</button>;
}
Nach dem Login kopieren

8. Rendering

Rendering is the process of React outputting the DOM elements to the browser. Components render UI based on props, state, and other data.

Example:

import ReactDOM from 'react-dom';

function App() {
  return <h1>Hello, React!</h1>;
}

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

Nach dem Login kopieren

9. Conditional Rendering

You can render different components or elements based on conditions.

Example:

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>;
}
Nach dem Login kopieren

10. Lists and Keys

In React, you can render lists of data using the map() method, and each list item should have a unique key.

Example:

function ItemList(props) {
  const items = props.items;
  return (
    <ul>
      {items.map(item => <li key={item.id}>{item.name}</li>)}
    </ul>
  );
}

const items = [
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Cherry' }
];

<ItemList items={items} />;

Nach dem Login kopieren

11. Lifting State Up

Sometimes, multiple components need to share the same state. You "lift the state up" to their nearest common ancestor so that it can be passed down as props.

Example:

function TemperatureInput({ temperature, onTemperatureChange }) {
  return (
    <input
      type="text"
      value={temperature}
      onChange={e => onTemperatureChange(e.target.value)}
    />
  );
}

function Calculator() {
  const [temperature, setTemperature] = useState('');

  return (
    <div>
      <TemperatureInput
        temperature={temperature}
        onTemperatureChange={setTemperature}
      />
      <p>The temperature is {temperature}°C.</p>
    </div>
  );
}

Nach dem Login kopieren

These are the basic concepts that form the foundation of React development.

Das obige ist der detaillierte Inhalt vonReact Basics. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!