快速入门

欢迎访问 React 文档!以下列表列出了你在本站点可以学习到的内容!

简介

以下是一个很简短的 React 程序。如果你是首次体验 React, 请编辑下面的代码 并使其显示你的名字:

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

export default function App() {
  return (
    <div>
      <Greeting name="Divyesh" />
      <Greeting name="Sarah" />
      <Greeting name="Taylor" />
    </div>
  );
}

React 是什么?

React 是一个用户构建用户界面的 JavaScript 工具库。

React 处于设计与编程的交叉点上。 它可以让你将一个复杂的用户界面分解为多个可以嵌套并重用的叫做 “组件” 的部分,这些部分可以很好地结合在一起。 如果你有编程背景的话,这可能会让你想起使用函数编写程序。如果你是一名设计师的话,这可能会让你想起使用层(layers)来做设计。如果你对这两门技术都没有经验的话,也没关系!很多人都是通过 React 入行的。使用 React 就像用玩具砖块建造城堡一样。有时候,这非常有趣。

React does not prescribe how you build your entire application. It helps you define and compose components, but stays out of your way in other questions. This means that you will either pick one of the ecosystem solutions for problems like routing, styling, and data fetching, or use a framework that provides great defaults.

你能用 React 做什么?

相当多,真的!人们使用 React 创建各种用户界面,小到按钮(buttons)和下拉列表(dropdowns)等组件,大到整个应用程序。本文档将教您如何在网站上使用 React。 并且,你在这里学到的大部分知识也同样适用于 React Native - 一个可以让你为 Android、iO,甚至 Windows 和 macOS 构建应用程序的框架。

如果你想知道每天所使用的应用程序中有哪些产品是用 React 构建的,可以安装 React Developer Tools 一探究竟。每当你访问一个应用程序或网站时,如果它是使用 React 构建的(比如本站点),工具条上的图标就会点亮。

React 是用 JavaScript 开发的

使用 React 时,你需要利用 JavaScript 来描述业务逻辑。这需要一些练习。如果你正在同时学习 JavaScript 和 React(很多人都是这样的),那么会遇到更多挑战!从好的方面来看,学习 React 很大程度上就是在学习 JavaScript,这意味着你所学到的远不止 React。

通过 这个 JavaScript 概述 可以检查一下你的知识水平。这将花费你 30 分钟到一小时的时间,但是会让你学习 React 时更加自信。MDNjavascript.info 是两份非常棒的参考资料。

Deep Dive

安装(可选)

学习 React

以下几种方法可以帮你快速入门:

  • 如果你 等不及了,想边做边学 的话,请直接进入 Thinking in React 章节。本教程不会详细解释语法,但是会让你大概了解使用 React 构建用户界面的思路。
  • 如果你 熟悉这些概念并希望浏览可用的 API 的话,请查看 API 参考手册
  • 本文档的其余部分分为多个章节,一步步地介绍 React 的每个概念,其中包含了许多交互式示例、重点详解以及课后考察。你不必按顺序阅读,但是每一章节都会假定你已经熟悉了前面章节中的概念。

为了节约时间,我们将在下面 简要概述每个章节的内容

第一章:描述 UI

React 应用程序是使用被称为 “组件(component)” 的独立 UI 片段组合而成的。一个 React 组件就是一个 JavaScript 函数,函数中可以使用 HTML 标签。组件可以小到一个按钮,也可以大到整个页面。在下面的示例中,Gallery 被称为 父(parent) 组件,其包含了三个叫做 Profile子(child) 组件:

function Profile() {
  return (
    <img
      src="https://i.imgur.com/MK3eW3As.jpg"
      alt="Katherine Johnson"
      className="avatar"
    />
  );
}

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}

The markup in the example above looks a lot like HTML. This syntax is called JSX, and it is a bit stricter (for example, you have to close all the tags). Note that the CSS class is specified as className in JSX.

Just like you can pass some information to the browser <img> tag, you can also pass information to your own components like <Profile>. Such information is called props. Here, three <Profile>s receive different props:

function Profile({ name, imageUrl }) {
  return (
    <img
      className="avatar"
      src={imageUrl}
      alt={name}
    />
  );
}

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile
        name="Lin Lanying"
        imageUrl="https://i.imgur.com/1bX5QH6.jpg"
      />
      <Profile
        name="Gregorio Y. Zara"
        imageUrl="https://i.imgur.com/7vQD0fPs.jpg"
      />
      <Profile
        name="Hedy Lamarr"
        imageUrl="https://i.imgur.com/yXOvdOSs.jpg"
      />
    </section>
  );
}

You might wonder why className="avatar" uses quotes but src={imageUrl} uses curly braces. In JSX, curly braces are like a “window into JavaScript”. They let you run a bit of JavaScript right in your markup! So src={imageUrl} reads the imageUrl prop declared on the first line and passed from the parent Gallery component.

In the above example, all the data was written directly in markup. However, you’ll often want to keep it separately. Here, the data is kept in an array. In React, you use JavaScript functions like map to render lists of things.

import { people } from './data.js';
import Profile from './Profile.js';

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      {people.map(person => (
        <Profile
          key={person.id}
          name={person.name}
          imageId={person.imageId}
        />
      ))}
    </section>
  );
}

Ready to learn this topic?

Read Describing the UI to learn how to make things appear on the screen, including declaring components, importing them, writing JSX with the curly braces, and writing conditions and lists.

Read More

Chapter 2 overview: Adding interactivity

Components often need to change what’s on the screen as a result of an interaction. Typing into the form should update the input field, clicking “next” on an image carousel should change which image is displayed, clicking “buy” puts a product in the shopping cart. Components need to “remember” things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called state.

You can add state to a component with a useState Hook. Hooks are special functions that let your components use React features (state is one of those features). The useState Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.

This Gallery component needs to remember two things: the current image index (initially, 0), and whether the user has toggled “Show details” (initially, false):

const [index, setIndex] = useState(0);
const [showMore, setShowMore] = useState(false);

Notice how clicking the buttons updates the screen:

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);
  const [showMore, setShowMore] = useState(false);

  function handleNextClick() {
    setIndex(index + 1);
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleNextClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i>
        by {sculpture.artist}
      </h2>
      <h3>
        ({index + 1} of {sculptureList.length})
      </h3>
      <button onClick={handleMoreClick}>
        {showMore ? 'Hide' : 'Show'} details
      </button>
      {showMore && <p>{sculpture.description}</p>}
      <img
        src={sculpture.url}
        alt={sculpture.alt}
      />
    </>
  );
}

State can hold complex values, too. For example, if you’re implementing a form, you can keep an object in state with different fields. The ... syntax in the below example lets you create new objects based on existing ones.

import { useState } from 'react';

export default function Form() {
  const [person, setPerson] = useState({
    firstName: 'Barbara',
    lastName: 'Hepworth',
    email: 'bhepworth@sculpture.com'
  });

  function handleFirstNameChange(e) {
    setPerson({
      ...person,
      firstName: e.target.value
    });
  }

  function handleLastNameChange(e) {
    setPerson({
      ...person,
      lastName: e.target.value
    });
  }

  function handleEmailChange(e) {
    setPerson({
      ...person,
      email: e.target.value
    });
  }

  return (
    <>
      <label>
        First name:
        <input
          value={person.firstName}
          onChange={handleFirstNameChange}
        />
      </label>
      <label>
        Last name:
        <input
          value={person.lastName}
          onChange={handleLastNameChange}
        />
      </label>
      <label>
        Email:
        <input
          value={person.email}
          onChange={handleEmailChange}
        />
      </label>
      <p>
        {person.firstName}{' '}
        {person.lastName}{' '}
        ({person.email})
      </p>
    </>
  );
}

You can also hold arrays in state. This lets you add, remove, or change things in a list in response to user interactions. Depending on what you want to do, there are different ways to make new arrays from existing ones.

import { useState } from 'react';

let nextId = 0;

export default function List() {
  const [name, setName] = useState('');
  const [artists, setArtists] = useState([]);

  return (
    <>
      <h1>Inspiring sculptors:</h1>
      <input
        value={name}
        onChange={e => setName(e.target.value)}
      />
      <button onClick={() => {
        setName('');
        setArtists([
          ...artists,
          { id: nextId++, name: name }
        ]);
      }}>Add</button>
      <ul>
        {artists.map(artist => (
          <li key={artist.id}>{artist.name}</li>
        ))}
      </ul>
    </>
  );
}

Ready to learn this topic?

Read Adding Interactivity to learn how to update the screen on interaction, including adding event handlers, declaring and updating state, and the different ways to update objects and arrays in state.

Read More

Chapter 3 overview: Managing state

You’ll often face a choice of what exactly to put into state. Should you use one state variable or many? An object or an array? How should you structure your state? The most important principle is to avoid redundant state. If some information never changes, it shouldn’t be in state. If some information is received from parent by props, it shouldn’t be in state. And if you can compute something from other props or state, it shouldn’t be in state either!

For example, this form has a redundant fullName state variable:

import { useState } from 'react';

export default function Form() {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [fullName, setFullName] = useState('');

  function handleFirstNameChange(e) {
    setFirstName(e.target.value);
    setFullName(e.target.value + ' ' + lastName);
  }

  function handleLastNameChange(e) {
    setLastName(e.target.value);
    setFullName(firstName + ' ' + e.target.value);
  }

  return (
    <>
      <h2>Let’s check you in</h2>
      <label>
        First name:{' '}
        <input
          value={firstName}
          onChange={handleFirstNameChange}
        />
      </label>
      <label>
        Last name:{' '}
        <input
          value={lastName}
          onChange={handleLastNameChange}
        />
      </label>
      <p>
        Your ticket will be issued to: <b>{fullName}</b>
      </p>
    </>
  );
}

You can remove it and simplify the code by calculating fullName while the component is rendering:

import { useState } from 'react';

export default function Form() {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');

  const fullName = firstName + ' ' + lastName;

  function handleFirstNameChange(e) {
    setFirstName(e.target.value);
  }

  function handleLastNameChange(e) {
    setLastName(e.target.value);
  }

  return (
    <>
      <h2>Let’s check you in</h2>
      <label>
        First name:{' '}
        <input
          value={firstName}
          onChange={handleFirstNameChange}
        />
      </label>
      <label>
        Last name:{' '}
        <input
          value={lastName}
          onChange={handleLastNameChange}
        />
      </label>
      <p>
        Your ticket will be issued to: <b>{fullName}</b>
      </p>
    </>
  );
}

This might seem like a small change, but many bugs in React apps are fixed this way!

Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as “lifting state up”, and it’s one of the most common things you will do writing React code. For example, in an accordion like below, only one panel should be active at a time. Instead of keeping the active state inside each individual panel, the parent component holds the state and specifies the props for its children.

import { useState } from 'react';

export default function Accordion() {
  const [activeIndex, setActiveIndex] = useState(0);
  return (
    <>
      <h2>Almaty, Kazakhstan</h2>
      <Panel
        title="About"
        isActive={activeIndex === 0}
        onShow={() => setActiveIndex(0)}
      >
        With a population of about 2 million, Almaty is Kazakhstan's largest city. From 1929 to 1997, it was its capital city.
      </Panel>
      <Panel
        title="Etymology"
        isActive={activeIndex === 1}
        onShow={() => setActiveIndex(1)}
      >
        The name comes from <span lang="kk-KZ">алма</span>, the Kazakh word for "apple" and is often translated as "full of apples". In fact, the region surrounding Almaty is thought to be the ancestral home of the apple, and the wild <i lang="la">Malus sieversii</i> is considered a likely candidate for the ancestor of the modern domestic apple.
      </Panel>
    </>
  );
}

function Panel({
  title,
  children,
  isActive,
  onShow
}) {
  return (
    <section className="panel">
      <h3>{title}</h3>
      {isActive ? (
        <p>{children}</p>
      ) : (
        <button onClick={onShow}>
          Show
        </button>
      )}
    </section>
  );
}

Ready to learn this topic?

Read Managing State to learn how to keep your components maintainable, including how to structure state well, how to share it between components, and how to pass it deep into the tree.

Read More

Next steps

This page was fast-paced! If you’ve read this far, you have already seen 80% of React you will use on a daily basis.

Your next steps depend on what you’d like to do:

  • Go to Installation if you’d like to set up a React project locally.
  • Read Thinking in React if you’d like to see what building a UI in React feels like in practice.
  • Or, start with Describing the UI to get a closer look at the first chapter.

And don’t forget to check the API Reference when you need the API without the fluff!