Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

React 列表


在 React 中,您将使用某种类型的循环来渲染列表。

JavaScript 的 map() 数组方法通常是首选方法。

如果您需要复习 map() 方法,请查看 ES6 部分


示例

让我们渲染我们车库中的所有汽车

function Car(props) {
  return <li>I am a { props.brand }</li>;
}

function Garage() {
  const cars = ['Ford', 'BMW', 'Audi'];
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <ul>
        {cars.map((car) => <Car brand={car} />)}
      </ul>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);

运行示例 »

当您在 create-react-app 中运行此代码时,它将工作,但您会收到一个警告,提示列表项没有提供“键”。


w3schools CERTIFIED . 2022

获得认证!

完成 React 模块,完成练习,参加考试并获得 w3schools 认证!!

95 美元 报名

键允许 React 跟踪元素。这样,如果更新或删除了某个项目,则只会重新渲染该项目,而不是整个列表。

键需要对每个同级元素唯一。但它们可以在全局范围内重复。

通常,键应该是分配给每个项目的唯一 ID。作为最后的手段,您可以使用数组索引作为键。

示例

让我们重构我们之前的示例以包含键

function Car(props) {
  return <li>I am a { props.brand }</li>;
}

function Garage() {
  const cars = [
    {id: 1, brand: 'Ford'},
    {id: 2, brand: 'BMW'},
    {id: 3, brand: 'Audi'}
  ];
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <ul>
        {cars.map((car) => <Car key={car.id} brand={car.brand} />)}
      </ul>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);

运行示例 »



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.