搜索 something KFeedback

[Learn React](/learn) 学习反应

Quick Start 快速开始

Welcome to the React documentation! This page will give you an introduction to the 80% of React concepts that you will use on a daily basis.

欢迎来到 React 文档!这个页面将给你一个介绍80% 的反应概念,你将使用的日常基础。

You will learn 你会学会的

  • How to create and nest components
  • How to add markup and styles
  • How to display data 如何显示数据
  • How to render conditions and lists
  • How to respond to events and update the screen
  • How to share data between components

Creating and nesting components 创建和嵌套组件

React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.

反应应用程序是由组件构成的。组件是 UI (用户界面)的一部分,它有自己的逻辑和外观。组件可以像按钮一样小,也可以像整个页面一样大。

React components are JavaScript functions that return markup:

组件是返回标记的 JavaScript 函数:

function MyButton() {  return (      );}

Now that you’ve declared MyButton, you can nest it into another component:

现在你已经声明了 MyButton,你可以把它嵌入到另一个组件中:

export default function MyApp() {  return (    

Welcome to my app


Notice that <MyButton /> starts with a capital letter. That’s how you know it’s a React component. React component names must always start with a capital letter, while HTML tags must be lowercase.

注意 < mybutton/> 以大写字母开头。这就是为什么你知道它是一个反应组件。反应组件名称必须始终以大写字母开头,而 HTML 标记必须是小写的。

Have a look at the result:


App.jsDownload ResetFork[1]

Jsdownload ResetFork [1]

To enter the code editing mode, press Enter. To exit the edit mode, press Escape

要进入代码编辑模式,请按 Enter。要退出编辑模式,请按 Escape

You are editing the code. To exit the edit mode, press Escape

您正在编辑代码。要退出编辑模式,请按 Escape

9912345678910111213141516function MyButton() {return ();}export default function MyApp() {return (

99123456789101111213141516function MyButton (){ return (Click me) ; } export default function MyApp (){ return ()

Welcome to my app



The export default keywords specify the main component in the file. If you’re not familiar with some piece of JavaScript syntax, MDN and javascript.info have great references.

导出默认关键字指定文件中的主要组件。如果你不熟悉一些 JavaScript 语法,MDN 和 JavaScript.info 有很好的参考。

Writing markup with JSX 用 JSX 编写标记

The markup syntax you’ve seen above is called JSX. It is optional, but most React projects use JSX for its convenience. All of the tools we recommend for local development support JSX out of the box.

上面看到的标记语法称为 JSX。它是可选的,但是大多数 React 项目为了方便使用 JSX。我们推荐的所有用于本地开发的工具都可以立即支持 JSX。

JSX is stricter than HTML. You have to close tags like <br />. Your component also can’t return multiple JSX tags. You have to wrap them into a shared parent, like a <div>...</div> or an empty <>...</> wrapper:

JSX 比 HTML 更严格。你必须关闭像。您的组件也不能返回多个 JSX 标记。你必须将它们包装到一个共享的父类中,比如 < div > ... </div > 或者一个空的 < </> 包装器:

function AboutPage() {  return (    <>      


Hello there.
How do you do?


If you have a lot of HTML to port to JSX, you can use an online converter.

如果有很多 HTML 要移植到 JSX,可以使用在线转换器。

Adding styles 添加样式

In React, you specify a CSS class with className. It works the same way as HTML class attribute:

在 React 中,你用 className 指定一个 CSS 类,它的工作方式与 HTML class 属性相同:

Then you write the CSS rules for it in a separate CSS file:

然后你在一个单独的 CSS 文件中为它编写 CSS 规则:

/* In your CSS */.avatar {  border-radius: 50%;}

React does not prescribe how you add CSS files. In the simplest case, you’ll add a <link> tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project.

反应不规定如何添加 CSS 文件。在最简单的情况下,您将向 HTML 中添加一个 < link > 标记。如果使用构建工具或框架,请参考其文档以了解如何向项目中添加 CSS 文件。

Displaying data 显示数据

JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will display user.name:

可以让你把标记放到 JavaScript 中。大括号可以让你“逃回”到 JavaScript 中,这样你就可以嵌入一些代码中的变量并显示给用户。例如,这将显示 user.name:

return (  



You can also “escape into JavaScript” from JSX attributes, but you have to use curly braces instead of quotes. For example, className="avatar" passes the "avatar" string as the CSS class, but src={user.imageUrl} reads the JavaScript user.imageUrl variable value, and then passes that value as the src attribute:

您还可以从 JSX 属性“转义到 JavaScript”,但是必须使用大括号而不是引号。例如,className = “ avatar”将“ avatar”字符串作为 CSS 类传递,但 src = { user.imageUrl }读取 javascriptuser.imageurl 变量值,然后将该值作为 src 属性传递:

return (  );

You can put more complex expressions inside the JSX curly braces too, for example, string concatenation:

你也可以把更复杂的表达式放在 JSX 的大括号中,例如,字符串连接:

App.jsDownload Reset




To enter the code editing mode, press Enter. To exit the edit mode, press Escape

要进入代码编辑模式,请按 Enter。要退出编辑模式,请按 Escape

You are editing the code. To exit the edit mode, press Escape

您正在编辑代码。要退出编辑模式,请按 Escape

9912345678910111213141516171819202122const user = {name: 'Hedy Lamarr',imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',imageSize: 90,};export default function Profile() {return (<>

9912345678910111213141516171819202122const user = { name: ‘ Hedy Lamarr’,imageUrl: ‘ https://i.imgur.com/yxovdoss.jpg’,imagesize : 90,} ; export default function Profile (){ return (< >


{ user.name }

<imgclassName="avatar"src={user.imageUrl}alt={'Photo of ' + user.name}style={{width: user.imageSize,height: user.imageSize}}/></>);}Show more “ avatar”= { user.imageUrl } alt = {‘ Photo of’+ user.name } style = { width: user.imageSize,height: user.imageSize }}/> </> ; } Show more

In the above example, style={{}} is not a special syntax, but a regular {} object inside the style={ } JSX curly braces. You can use the style attribute when your styles depend on JavaScript variables.

在上面的例子中,style = {{}}不是一个特殊的语法,而是 style = {} JSX 花括号中的一个正则{}对象。当样式依赖于 JavaScript 变量时,可以使用 style 属性。

Conditional rendering 条件呈现

In React, there is no special syntax for writing conditions. Instead, you’ll use the same techniques as you use when writing regular JavaScript code. For example, you can use an if statement to conditionally include JSX:

在 React 中,没有针对写入条件的特殊语法。相反,您将使用与编写常规 JavaScript 代码时相同的技术。例如,可以使用 if 语句有条件地包含 JSX:

let content;if (isLoggedIn) {  content = 
   ;} else {  content = 
    ;}return (  

If you prefer more compact code, you can use the conditional ? operator. Unlike if, it works inside JSX:

如果您喜欢更紧凑的代码,可以使用 conditional? 操作符:

{isLoggedIn ? ( ) : ( )}

When you don’t need the else branch, you can also use a shorter logical && syntax:

当你不需要 else 分支的时候,你也可以使用一个简短的逻辑 & 语法:

{isLoggedIn && }

All of these approaches also work for conditionally specifying attributes. If you’re unfamiliar with some of this JavaScript syntax, you can start by always using if...else.

所有这些方法也适用于有条件地指定属性。如果你不熟悉这些 JavaScript 语法,你可以从使用 If... else 开始。

Rendering lists 渲染列表

You will rely on JavaScript features like for loop and the array map() function to render lists of components.

您将依赖诸如 for 循环和 array map ()函数之类的 JavaScript 特性来呈现组件列表。

For example, let’s say you have an array of products:


const products = [  { title: 'Cabbage', id: 1 },  { title: 'Garlic', id: 2 },  { title: 'Apple', id: 3 },];

Inside your component, use the map() function to transform an array of products into an array of <li> items:

在组件内部,使用 map ()函数将产品数组转换为 < li > 项目数组:

const listItems = products.map(product =>  
  • {product.title}
  • );return (

    Notice how <li> has a key attribute. For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React will rely on your keys to understand what happened if you later insert, delete, or reorder the items.

    注意 < li > 有一个关键属性。对于列表中的每个项,应该传递一个字符串或数字,该字符串或数字在其兄弟项中唯一地标识该项。通常,一个密钥应该来自您的数据,比如数据库 ID。如果您稍后插入、删除或重新排序项目,响应将依赖于您的键来理解发生了什么。

    App.jsDownload Reset




    To enter the code editing mode, press Enter. To exit the edit mode, press Escape

    要进入代码编辑模式,请按 Enter。要退出编辑模式,请按 Escape

    You are editing the code. To exit the edit mode, press Escape

    您正在编辑代码。要退出编辑模式,请按 Escape

    9912345678910111213141516171819202122const products = [{ title: 'Cabbage', isFruit: false, id: 1 },{ title: 'Garlic', isFruit: false, id: 2 },{ title: 'Apple', isFruit: true, id: 3 },];export default function ShoppingList() {const listItems = products.map(product =><likey={product.id}style={{color: product.isFruit ? 'magenta' : 'darkgreen'}}>{product.title});return (

    9912345678910111213141516171819202122const products = [{ title: ‘ Cabbage’,isFruit: false,id: 1} ,{ title: ‘ Garlic’,isFruit: false,id: 2} ,{ title: ‘ Apple’,isFruit: true,id: 3} ,] ; export default function ShoppingList (){ const ems = products.map (product = > likey = { product.id: style = { color: product.isFruit?{ product.title }) ; return (

      {listItems} 10. 你可以在这里找到你想要的
    );}Show more 展示更多

    Responding to events 对事件的反应

    You can respond to events by declaring event handler functions inside your components:


    function MyButton() {  function handleClick() {    alert('You clicked me!');  }  return (      );}

    Notice how onClick={handleClick} has no parentheses at the end! Do not call the event handler function: you only need to pass it down. React will call your event handler when the user clicks the button.

    注意 onClick = { handleClick }最后没有括号!不要调用事件处理程序函数: 您只需要将其传递下去。当用户单击按钮时,React 将调用事件处理程序。

    Updating the screen 更新屏幕

    Often, you’ll want your component to “remember” some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add state to your component.


    First, import useState from React:

    首先,从 React 导入 useState:

    import { useState } from 'react';

    Now you can declare a state variable inside your component:


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

    You will get two things from useState: the current state (count), and the function that lets you update it (setCount). You can give them any names, but the convention is to call them like [something, setSomething].

    您将从 useState 获得两个信息: 当前状态(count)和允许更新它的函数(setCount)。你可以给他们起任何名字,但惯例是这样叫他们[ something,setSomething ]。

    The first time the button is displayed, count will be 0 because you passed 0 to useState(). When you want to change state, call setCount() and pass the new value to it. Clicking this button will increment the counter:

    第一次显示按钮时,计数将为0,因为您将0传递给了 useState ()。当您想要更改状态时,调用 setCount ()并将新值传递给它。点击这个按钮会增加计数器:

    function MyButton() {  const [count, setCount] = useState(0);  function handleClick() {    setCount(count + 1);  }  return (      );}

    React will call your component function again. This time, count will be 1. Then it will be 2. And so on.

    React 将再次调用组件函数。这一次,计数将是1。那就是2了。诸如此类。

    If you render the same component multiple times, each will get its own state. Try clicking each button separately:


    App.jsDownload Reset




    To enter the code editing mode, press Enter. To exit the edit mode, press Escape

    要进入代码编辑模式,请按 Enter。要退出编辑模式,请按 Escape

    You are editing the code. To exit the edit mode, press Escape

    您正在编辑代码。要退出编辑模式,请按 Escape

    991234567891011121314151617181920212223242526import { useState } from 'react';function MyButton() {const [count, setCount] = useState(0);function handleClick() {setCount(count + 1);}return ();}export default function MyApp() {return (

    99123456789101112131415161718192021223242526import { useState } from‘ react’; function MyButton (){ const [ count,setCount ] = useState (0) ; function handleClick (){ setCount (count + 1) ; } return (Clicked { count } times) ; } export function MyApp (){ return ())

    Counters that update separately


    );}Show more 展示更多

    Notice how each button “remembers” its own count state and doesn’t affect other buttons.


    Using Hooks 使用钩子

    Functions starting with use are called Hooks. useState is a built-in Hook provided by React. You can find other built-in Hooks in the React API reference. You can also write your own Hooks by combining the existing ones.

    从 use 开始的函数称为 Hooks。useState 是 React 提供的内置钩子。您可以在 React API 参考中找到其他内置的 Hooks。您还可以通过组合现有的 hook 来编写自己的 hook。

    Hooks are more restrictive than regular functions. You can only call Hooks at the top level of your components (or other Hooks). If you want to useState in a condition or a loop, extract a new component and put it there.

    钩子比常规函数限制性更强。您只能在组件的顶层调用 Hooks (或其他 Hooks)。如果希望在条件或循环中使用 useState,请提取一个新组件并将其放在那里。

    Sharing data between components 在组件之间共享数据

    In the previous example, each button had its own independent counter:


    - MyApp  - MyButton (count: 3)  - MyButton (count: 1)  - MyButton (count: 2)

    However, you’ll often need components to share data and always update together.


    To make all buttons display the same count and update together, you need to move the state from the individual buttons “upwards” to the closest component containing all of them. In this example, it is MyApp:

    要使所有按钮显示相同的计数并一起更新,您需要将状态从单个按钮“向上”移动到包含所有按钮的最近组件。在这个例子中,它是 MyApp:

    - MyApp (count: 3)  - MyButton  - MyButton  - MyButton

    Here’s how you can express this in code.


    First, move the state up from MyButton into MyApp:

    首先,把政府从 MyButton 移到 MyApp:

    function MyButton() {  // ... we're moving code from here ...}export default function MyApp() {  const [count, setCount] = useState(0);  function handleClick() {    setCount(count + 1);  }  return (    

    Counters that update separately


    Then, pass the state down from MyApp to each MyButton, together with the shared click handler. You can pass information to MyButton using the JSX curly braces, just like you previously did with built-in tags like <img>:

    然后,将状态从 MyApp 传递给每个 MyButton,同时使用共享单击处理程序。您可以使用 JSX 大括号将信息传递给 MyButton,就像您以前使用像 < img > 这样的内置标记所做的一样:

    export default function MyApp() {  const [count, setCount] = useState(0);  function handleClick() {    setCount(count + 1);  }  return (    

    Counters that update together


    The information you pass down like this is called props. Now the MyApp component contains the count state and the handleClick event handler, and passes both of them down as props to each of the buttons.

    像这样传递下去的信息叫做道具。现在,MyApp 组件包含 count 状态和 handleClick 事件处理程序,并将它们作为道具传递给每个按钮。

    Finally, change MyButton to read the props you have passed from its parent component:

    最后,修改 MyButton 来读取你从它的父组件中传递过来的道具:

    function MyButton({ count, onClick }) {  return (      );}

    When you click the button, the onClick handler fires. Each button’s onClick prop was set to the handleClick function inside MyApp, so the code inside of it runs. That code calls setCount(count + 1), incrementing the count state variable. The new count value is passed as a prop to each button, so they all show the new value.

    当您单击该按钮时,onClick 处理程序将触发。每个按钮的 onClick 道具都被设置为 MyApp 内部的 handleClick 函数,因此它内部的代码可以运行。该代码调用 setCount (count + 1) ,递增 count 状态变量。新的计数值作为一个道具传递给每个按钮,因此它们都显示新的值。

    This is called “lifting state up”. By moving state up, we’ve shared it between components.


    App.jsDownload Reset




    To enter the code editing mode, press Enter. To exit the edit mode, press Escape

    要进入代码编辑模式,请按 Enter。要退出编辑模式,请按 Escape

    You are editing the code. To exit the edit mode, press Escape

    您正在编辑代码。要退出编辑模式,请按 Escape

    991234567891011121314151617181920212223242526import { useState } from 'react';function MyButton({ count, onClick }) {return ();}export default function MyApp() {const [count, setCount] = useState(0);function handleClick() {setCount(count + 1);}return (

    99123456789101112131415161718192021223242526import { useState } from‘ react’; function MyButton ({ count,onClick }){ return (Clicked { count } times; } export default function MyApp (){ const [ count,setCount ] = useState (0) ; function handleClick (){ setCount (count + 1) ; } return ()

    Counters that update together


    );}Show more 展示更多

    Next Steps 下一步

    By now, you know the basics of how to write React code!

    现在,您已经知道了如何编写 React 代码的基本知识!

    Head to Thinking in React to see how it feels to build a UI with React in practice.

    前往 Thinking in React,看看在实践中使用 React 构建 UI 是什么感觉。

    Open Source©2022Learn ReactQuick StartInstallationDescribing the UIAdding InteractivityManaging StateEscape HatchesAPI ReferenceReact APIsReact DOM APIsCommunityCode of ConductAcknowledgementsMeet the TeamMoreReact NativePrivacyTerms

    开放源码2022学习反应快速开始安装描述用户界面添加互动管理状态/逃逸帽/api 参考文献/参考文献/行为/行为/反应/行为/行为/行为/行为/行为/知识/行为/行为/行为/行为/行为/行为/行为/行为/行为


    Drag and drop the image to complete the download



    Open in CodeSandbox: https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKAggBzQOgFYOSAYwHsA7AFxnKXAFcSCyJSACAWQE8AhGss0gCgCUzYAB0SzZgCcYZGlIn9xkyQB4ARjz4kAfMpWSAwlAgEA1swC2MfWoD0m3qT0TmggNziAvuPEwAHmhEUmTMACYwYACGNFChYHQMTBIc6GhCIvoycgrMSq5qYRAAbi4GagAWAIw6AOowUMTWzHxW7MxRGKp21WXlqhzcThJ2ffZFpfoe3iAANCAQcJwQJFFS7EjRUHAwXvMrEf44eKDE5JRk1BCWQSHMAEowUQyzIswAymRSpmSsRBHMLzMMBSIiWZiiEAyZ5kSGeEjXW6hR4wgAiAHlWMDQeDIdCGABaMJguHiRHBUKQzB2OBkdiwOCYAhwOCkkhkm4U5hpbFgiEgalpNniM606REIhkACisGs5GYAF5wkQCDQ5WRMABzWQymDqzjsACSYSUUIlsJA0xIKIYGNYmBkJAiUnyak-3wYfwiY2Yqh5o303XdPy9MB0syy5t16vEHjmCyWKzWG0QWx2exAtPp8CZLKQp1IFCoiBAACpMq51ER_AS4BAAF4rTWIZhVqTOglV_zwnzskhVsLtMSuMCFgnRSzQdgtuBREhwWswb5geGSSxrTUrFsAJgADGhu_o0FEwkUSM3mLue74SNUK2uNysCXw0C2r_pR-Raw2YDvtwfrz7Cpt3vKxHxIZ8iFfS9V2BMc63rX9mD3ADvBvCoAGZQPXKRNwgl831gz8yG_RCWyqAAOVCSF7cQKgAFmw8DIOg98R3gn9yIANmo2jbwAViY3CnwImCPw4sjmCqejePQrihLwljCPEr8EKQqp_0PGib1iUDj1PJsCVgMAyB3fctL4-NFmWVZ1k2KJtl2eY0BodQTAIOwDgCTAKjISwoHzQhCwuahVAAQgxQwABUAE0AAUpWYXz_JcVRkqgZgoDnTUFUhShIT6NKnjCH1VGsMgomYAgKjWHYyFykAAFUooAMQJCiCtsX1ysq1ZrAa4oIBgAB3JFISq4LyAa4aIDCMgKgVCJBoIGACRmuaKleFYIEYBzawIByYAVKpMF3TqCl9RgyFgHRURVNULm6K6bsDHpisKgd2FKiZmFmhrQUlArugmQqHH-L7xG6dKdCsxNbJTNMnJAY9zCibVjlIQKziLS4S2HSRIT6mwkH5WcnRRswCTQUFsBgBhIQjVxIXXFZIRbSFPKdbzcAZ_RIQiNBKAieghtZEn8ZUPEnnpknIQAPSqAB2U7Tt5i6pZhIkSVlkAFeV3dVbmLqNcJOACG-NAyDF9ndfolWzpAfQ9j5kAltRGBBa5kX4DZkRey8WGbOTezHK8DMKBuLKKGoc2ngoAl8RIzo0BALwgA&query=file=/App.js%26from-sandpack=true

    在 CodeSandbox 中打开: https://CodeSandbox.io/api/v1/sandboxes/define?parameters=n4igzglgngpgziaxkaggbzqogfyosaywhsa7afxnkxafcscyjsacawqe8ahgss0gcgcuzyab0szzgccyzglin9xkyqb4arjz4kafmpwsawlagea1swc2mfwod0m3qt0tmggnziavupewahmheumtmacywyacgnfchyhqmtbic6ghcivoycgrmsq5qyraabi4gagawaiw6aoowumtwzhxw7mxrgkp21wxlqhzcthj2ffzfpfoe3iaancaqcjwqjffs7ejruhawxvmref44ekde5jrk1bcwqshmaeowuqyziswaymrspmssrbhmlzmmbsiiwziieayz5ksgeejxw6hr4wgaiahlwmdqedidcgabamjguhirhbukqzb2obkdiwocyahwockkhkm4u5hpbfgiegalpnnim606reihkacisgs5gyaf5wkqcdq5wrmabzwqymdqzjsacsysuuilsja0xikiygnymbkjaiunyak-3wyfwiy2yqh5o303xdpy9mb0syy5t16vehjmcywkzwg0qwx2exatpp8czlkqp1ifcoibaacpmq51er_as4baaf4rtwizhvqtoglv_zwnzskhvsltmsumcfgnrszqdgtubrehwwswb5gegssxrturfsajgadghu_o0fewkusm3mlue74snuk2unyscxw0c2r_pr-raw2ydvtwfrz7cpt3vkxhxiz8iffs9v2bmc63rx9md3advbvcoagzqpxkrnwgl831gz8yg_rcwyqaaovcsf7cqkgafmw8diog98r3gn9yianmo2jbwaviy3cnwimcpw4sjmcqejepqrihlwljcper8ekqqp_0pgib1iudj1pjscvgmayb3fctl4-nfmwvz1k2kjtl2ey0bodqtaiowdgctakjiswohzqhcwuahvaaqgxqwabuae0aaupwyxz_jcvrkqgzgodntufuhshit6nknjch1vgsmgomyagkjwhyyfykaafuooamqjcictsx1ysq1zraa4oibgab3jfisq4lyaa4aidcmgkgvcjboigacrmuaklefyieybzawibyyavkpmf3tqcl9rgyfghrurvnulm6k6bsdhpiskgd2fkizmfmhrqularugmqqhh-l7xg6dkdcsxnbjtnmnjay9zcibvjliqkzils4s2hsrit6mwkh5wcnrrswctqufsbgbhiqjvxixxfzirbsfpkdbzcaz_riqinbkaieghtzen8zupennpkniqapsqab2u7tt5i6pzhiksvlkafev3dvbmlqncjoacg-naydf9ndfolwzpafq9j5kaltrgbba5kx4dzkrey8wgbotezhk8dmkbulkkgoc2ngoal8rizo0balwga&query=file=/app.js%26from-sandpack=true