博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
react 组件中使用组件_如何使用道具定制React组件
阅读量:2511 次
发布时间:2019-05-11

本文共 33844 字,大约阅读时间需要 112 分钟。

react 组件中使用组件

The author selected to receive a donation as part of the program.

作者选择了来接受捐赠,这是计划的一部分。

介绍 (Introduction)

In this tutorial, you’ll create custom components by passing props to your component. Props are arguments that you provide to a . They look like standard HTML props, but they aren’t predefined and can have many different including numbers, strings, , , and even other . Your custom components can use props to display data or use the data to make the components interactive. Props are a key part of creating components that are adaptable to different situations, and learning about them will give you the tools to develop custom components that can handle unique situations.

在本教程中,您将通过将道具传递到组件来创建自定义组件。 道具是您提供给 。 它们看起来像标准HTML道具,但它们不是预定义的,可以具有许多不同的包括数字,字符串, , ,甚至其他 。 您的自定义组件可以使用道具显示数据或使用数据使组件具有交互性。 道具是创建可适应不同情况的组件的关键部分,了解它们将为您提供开发可处理特殊情况的自定义组件的工具。

After adding props to your component, you will use PropTypes to define the type of data you expect a component to receive. PropTypes are a simple type system to check that data matches the expected types during runtime. They serve as both documentation and an error checker that will help keep your application predictable as it scales.

将道具添加到组件后,将使用PropTypes定义希望组件接收的数据类型。 PropTypes是一个简单的类型系统,可以在运行时检查数据是否与期望的类型匹配。 它们既充当文档,又充当错误检查器,可帮助您在扩展应用程序时保持可预测性。

By the end of the tutorial, you’ll use a variety of props to build a small application that will take an array of animal data and display the information, including the name, scientific name, size, diet, and additional information.

在本教程结束时,您将使用各种props来构建一个小型应用程序,该应用程序将获取一系列动物数据并显示信息,包括名称,学名,大小,饮食和其他信息。

Note: The first step sets up a blank project on which you will build the tutorial exercise. If you already have a working project and want to go directly to working with props, start with .

注意 :第一步将设置一个空白项目,您将在该项目上构建本教程练习。 如果您已经有一个正在运行的项目,并且想直接使用道具,请从开始。

先决条件 (Prerequisites)

  • You will need a development environment running ; this tutorial was tested on Node.js version 10.20.1 and npm version 6.14.4. To install this on macOS or Ubuntu 18.04, follow the steps in or the Installing Using a PPA section of .

    您将需要一个运行的开发环境; 本教程已在Node.js 10.20.1版和npm 6.14.4版上进行了测试。 要将其安装在macOS或Ubuntu 18.04上,请遵循的步骤,或 使用PPA安装部分中的 。

  • In following this tutorial, you will use . You can find instructions for installing an application with Create React App at . This tutorial also assumes a knowledge of React components, which you can learn about in our tutorial.

    在学习本教程之后,您将使用 。 您可以在使用创建React App 找到有关使用Create React App安装应用程序的说明。 本教程还假设您具有React组件的知识,您可以在我们的《 教程中学习。

  • You will also need to know the basics of JavaScript, which you can find in , along with a basic knowledge of HTML and CSS. A good resource for HTML and CSS is the .

    您还需要了解的基础知识,以及HTML和CSS的基础知识,这些基础知识可以在找到。 是HTML和CSS的良好资源。

第1步-创建一个空项目 (Step 1 — Creating an Empty Project)

In this step, you’ll create a new project using . Then you will delete the sample project and related files that are installed when you bootstrap the project. Finally, you will create a simple file structure to organize your components.

在这一步中,您将使用创建一个新项目。 然后,您将删除示例项目以及在引导项目时安装的相关文件。 最后,您将创建一个简单的文件结构来组织您的组件。

To start, make a new project. In your command line, run the following script to install a fresh project using create-react-app:

首先,创建一个新项目。 在命令行中,运行以下脚本以使用create-react-app安装新项目:

  • npx create-react-app prop-tutorial

    npx create-react-app 用法说明

After the project is finished, change into the directory:

项目完成后,转到目录:

  • cd prop-tutorial

    cd 教程

In a new terminal tab or window, start the project using the . The browser will autorefresh on changes, so leave this script running the whole time that you work:

在新的终端标签或窗口中,使用启动项目。 浏览器将自动刷新更改,因此请在您工作期间始终运行以下脚本:

  • npm start

    npm开始

You will get a running local server. If the project did not open in a browser window, you can open it by navigating to . If you are running this from a remote server, the address will be http://your_domain:3000.

您将获得正在运行的本地服务器。 如果未在浏览器窗口中打开项目,则可以通过导航到来打开它。 如果您是从远程服务器运行的,则该地址将为http:// your_domain :3000

Your browser will load with a simple React application included as part of Create React App:

您的浏览器将加载一个简单的React应用程序,该应用程序是Create React App的一部分:

You will be building a completely new set of custom components. You’ll start by clearing out some boilerplate code so that you can have an empty project.

您将构建一套全新的自定义组件。 您将首先清除一些样板代码,以便拥有一个空项目。

To start, open src/App.js in a text editor. This is the root component that is injected into the page. All components will start from here. You can find more information about App.js at .

首先,在文本编辑器中打开src/App.js 这是注入页面的根组件。 所有组件将从此处开始。 您可以在找到有关App.js更多信息。

Open src/App.js with the following command:

使用以下命令打开src/App.js

  • nano src/App.js

    纳米src / App.js

You will see a file like this:

您将看到如下文件:

prop-tutorial/src/App.js
prop-tutorial / src / App.js
import React from 'react';import logo from './logo.svg';import './App.css';function App() {  return (    
logo

Edit src/App.js and save to reload.

Learn React
);}export default App;

Delete the line import logo from './logo.svg';. Then replace everything in the return statement to return a set of empty tags: <></>. This will give you a validate page that returns nothing. The final code will look like this:

import logo from './logo.svg';删除行import logo from './logo.svg'; 。 然后替换return语句中的所有内容以返回一组空标签: <></> 。 这将为您提供一个不返回任何内容的验证页面。 最终代码如下所示:

prop-tutorial/src/App.js
prop-tutorial / src / App.js
import React from 'react';import './App.css';function App() {  return <>;}export default App;

Save and exit the text editor.

保存并退出文本编辑器。

Finally, delete the logo. You won’t be using it in your application and you should remove unused files as you work. It will save you from confusion in the future.

最后,删除徽标。 您将不会在应用程序中使用它,并且应在工作时删除未使用的文件。 它将使您免于将来的混乱。

In the terminal window type the following command:

在终端窗口中,输入以下命令:

  • rm src/logo.svg

    rm src / logo.svg

If you look at your browser, you will see a blank screen.

如果您查看浏览器,将会看到一个空白屏幕。

Now that you have cleared out the sample Create React App project, create a simple file structure. This will help you keep your components isolated and independent.

现在,您已经清除了示例创建React App项目,创建一个简单的文件结构。 这将帮助您使组件保持隔离和独立。

Create a directory called components in the src directory. This will hold all of your custom components.

src目录中创建一个名为components的目录。 这将保存您所有的自定义组件。

  • mkdir src/components

    mkdir src /组件

Each component will have its own directory to store the component file along with the styles, images if there are any, and tests.

每个组件都有其自己的目录,用于存储组件文件以及样式,图像(如果有)和测试。

Create a directory for App:

App创建目录:

  • mkdir src/components/App

    mkdir src / components / App

Move all of the App files into that directory. Use the wildcard, *, to select any files that start with App. regardless of file extension. Then use the mv command to put them into the new directory.

将所有App文件移到该目录。 使用通配符*来选择以App.开头的任何文件App. 无论文件扩展名如何。 然后使用mv命令将它们放入新目录。

  • mv src/App.* src/components/App

    mv src / App。* src / components / App

Finally, update the relative import path in index.js, which is the root component that bootstraps the whole process.

最后,更新index.js的相对导入路径,它是引导整个过程的根组件。

  • nano src/index.js

    纳米src / index.js

The import statement needs to point to the App.js file in the App directory, so make the following highlighted change:

import语句需要指向App目录中的App.js文件,因此请进行以下突出显示的更改:

prop-tutorial/src/index.js
prop-tutorial / src / index.js
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './components/App/App';import * as serviceWorker from './serviceWorker';ReactDOM.render(  
, document.getElementById('root'));// If you want your app to work offline and load faster, you can change// unregister() to register() below. Note this comes with some pitfalls.// Learn more about service workers: https://bit.ly/CRA-PWAserviceWorker.unregister();

Save and exit the file.

保存并退出文件。

Now that the project is set up, you can create your first component.

现在已经建立了项目,您可以创建第一个组件。

第2步-使用道具构建动态组件 (Step 2 — Building Dynamic Components with Props)

In this step, you will create a component that will change based on the input information called props. Props are the arguments you pass to a function or class, but since your components are transformed into HTML-like objects with JSX, you will pass the props like they are HTML attributes. Unlike HTML elements, you can pass many different data types, from strings, to arrays, to objects, and even functions.

在此步骤中,您将创建一个组件,该组件将根据称为props的输入信息进行更改。 道具是传递给函数或类的参数,但是由于您的组件已通过JSX转换为类似HTML的对象,因此您将像把它们作为HTML属性一样传递道具。 与HTML元素不同,您可以传递许多不同的数据类型,从字符串,数组,对象甚至函数。

Here you will create a component that will display information about animals. This component will take the name and scientific name of the animal as strings, the size as an integer, the diet as an array of strings, and additional information as an object. You’ll pass the information to the new component as props and consume that information in your component.

在这里,您将创建一个组件,该组件将显示有关动物的信息。 该组件将把动物的名称和科学名称作为字符串,将大小作为整数,将饮食作为字符串数组,并将其他信息作为对象。 您会将信息作为道具传递给新组件,并在组件中使用该信息。

By the end of this step, you’ll have a custom component that will consume different props. You’ll also reuse the component to display an array of data using a common component.

在此步骤结束时,您将拥有一个将使用不同道具的自定义组件。 您还将使用通用组件重用该组件以显示数据数组。

新增资料 (Adding Data)

First, you need some sample data. Create a file in the src/App directory called data.

首先,您需要一些样本数据。 在src/App目录中创建一个名为data的文件。

  • touch src/components/App/data.js

    触摸src / components / App / data.js

Open the new file in your text editor:

在文本编辑器中打开新文件:

  • nano src/components/App/data.js

    纳米src / components / App / data.js

Next, add an array of you will use as sample data:

接下来,添加将用作示例数据的数组:

prop-tutorial/src/components/App/data.js
prop-tutorial / src / components / App / data.js
export default [  {    name: 'Lion',    scientificName: 'Panthero leo',    size: 140,    diet: ['meat'],  },  {    name: 'Gorilla',    scientificName: 'Gorilla beringei',    size: 205,    diet: ['plants', 'insects'],    additional: {      notes: 'This is the eastern gorilla. There is also a western gorilla that is a different species.'    }  },  {    name: 'Zebra',    scientificName: 'Equus quagga',    size: 322,    diet: ['plants'],    additional: {      notes: 'There are three different species of zebra.',      link: 'https://en.wikipedia.org/wiki/Zebra'    }  }]

The array of objects contains a variety of data and will give you an opportunity to try a variety of props. Each object is a separate animal with the name of the animal, the scientific name, size, diet, and an optional field called additional, which will contain links or notes. In this code, you also exported the array as the default.

对象数组包含各种数据,将使您有机会尝试各种道具。 每个对象都是单独的动物,具有动物名称,科学名称,大小,饮食以及一个可选字段(称为additional ,其中包含链接或注释。 在此代码中,您还将数组导出为default

Save and exit the file.

保存并退出文件。

创建组件 (Creating Components)

Next, create a placeholder component called AnimalCard. This component will eventually take props and display the data.

接下来,创建一个名为AnimalCard的占位符组件。 该组件最终将使用道具并显示数据。

First, make a directory in src/components called AnimalCard then touch a file called src/components/AnimalCard/AnimalCard.js and a CSS file called src/components/AnimalCard/AnimalCard.css.

首先,在一个目录src/components称为AnimalCard然后touch一个名为src/components/AnimalCard/AnimalCard.js并称为CSS文件src/components/AnimalCard/AnimalCard.css

  • mkdir src/components/AnimalCard

    mkdir src / components / AnimalCard
  • touch src/components/AnimalCard/AnimalCard.js

    触摸src / components / AnimalCard / AnimalCard.js
  • touch src/components/AnimalCard/AnimalCard.css

    触摸src / components / AnimalCard / AnimalCard.css

Open AnimalCard.js in your text editor:

在文本编辑器中打开AnimalCard.js

  • nano src/components/AnimalCard/AnimalCard.js

    纳米src / components / AnimalCard / AnimalCard.js

Add a basic component that imports the CSS and returns an <h2> tag.

添加一个导入CSS并返回<h2>标签的基本组件。

prop-tutorial/src/components/AnimalCard/AnimalCard.js
prop-tutorial / src / components / AnimalCard / AnimalCard.js
import React from 'react';import './AnimalCard.css'export default function AnimalCard() {  return 

Animal

}

Save and exit the file. Now you need to import the data and component into your base App component.

保存并退出文件。 现在,您需要将数据和组件导入到基本App组件中。

Open src/components/App/App.js:

打开src/components/App/App.js

  • nano src/components/App/App.js

    纳米src / components / App / App.js

Import the data and the component, then loop over the data returning the component for each item in the array:

导入数据和组件,然后遍历数据,返回数组中每个项目的组件:

prop-tutorial/src/components/App/App.js
prop-tutorial / src / components / App / App.js
import React from 'react';import data from './data';import AnimalCard from '../AnimalCard/AnimalCard';import './App.css';function App() {  return (    

Animals

{data.map(animal => (
))}
)}export default App;

Save and exit the file. Here, you use the to iterate over the data. In addition to adding this loop, you also have a wrapping div with a class that you will use for styling and an <h1> tag to label your project.

保存并退出文件。 在这里,您可以使用遍历数据。 除了添加此循环外,您还具有一个包装div其中包含将用于样式设置的类和一个<h1>标记来标记项目。

When you save, the browser will reload and you’ll see a label for each card.

保存后,浏览器将重新加载,并且您会看到每张卡的标签。

Next, add some styling to line up the items. Open App.css:

接下来,添加一些样式来排列项目。 打开App.css

  • nano src/components/App/App.css

    纳米src / components / App / App.css

Replace the contents with the following to arrange the elements:

将内容替换为以下内容以排列元素:

prop-tutorial/src/components/App/App.css
prop-tutorial / src / components / App / App.css
.wrapper {    display: flex;    flex-wrap: wrap;    justify-content: space-between;    padding: 20px;}.wrapper h1 {    text-align: center;    width: 100%;}

This will use to rearrange the data so it will line up. The padding gives some space in the browser window. justify-content will spread out the extra space between elements, and .wrapper h1 will give the Animal label the full width.

这将使用重新排列数据,以便将其 。 padding在浏览器窗口中留出一些空间。 justify-content将在元素之间扩展多余的空间, .wrapper h1将为Animal标签提供完整宽度。

Save and exit the file. When you do, the browser will refresh and you’ll see some data spaced out.

保存并退出文件。 完成后,浏览器将刷新,并且您会看到一些数据间隔开了。

添加道具 (Adding Props)

Now that you have your components set up, you can add your first prop. When you looped over your data, you had access to each object in the data array and the items it contained. You will add each piece of the data to a separate prop that you will then use in your AnimalCard component.

现在您已经设置了组件,可以添加第一个道具。 遍历数据时,您可以访问data数组中的每个对象及其包含的项目。 您会将每条数据添加到单独的道具中,然后将其用于AnimalCard组件中。

Open App.js:

打开App.js

  • nano src/components/App/App.js

    纳米src / components / App / App.js

Add a prop of name to AnimalCard.

AnimalCard添加name AnimalCard

prop-tutorial/src/components/App/App.js
prop-tutorial / src / components / App / App.js
import React from 'react';...function App() {  return (    

Animals

{data.map(animal => (
))}
)}export default App;

Save and exit the file. The name prop looks like a standard HTML attribute, but instead of a string, you’ll pass the name property from the animal object in curly braces.

保存并退出文件。 name道具看起来像标准HTML属性,但不是字符串,而是用花括号将animal对象的name属性传递给它。

Now that you’ve passed one prop to the new component, you need to use it. Open AnimalCard.js:

现在,您已经将一个道具传递给了新组件,您需要使用它。 打开AnimalCard.js

  • nano src/components/AnimalCard/AnimalCard.js

    纳米src / components / AnimalCard / AnimalCard.js

All props that you pass into the component are collected into an object that will be the first argument of your function. the object to pull out individual props:

您传递给组件的所有道具都被收集到一个对象中,该对象将成为函数的第一个参数。 对象以拉出各个道具:

prop-tutorial/src/components/AnimalCard/AnimalCard.js
prop-tutorial / src / components / AnimalCard / AnimalCard.js
import React from 'react';import './AnimalCard.css'export default function AnimalCard(props) {  const { name } = props;  return (    

{name}

);}

Note that you do not need to destructure a prop to use it, but that this is a useful method for dealing with the sample data in this tutorial.

请注意,您无需解构道具即可使用它,但是在本教程中,这是处理样本数据的有用方法。

After you destructure the object, you can use the individual pieces of data. In this case, you’ll use the title in an <h2> tag, surrounding the value with curly braces so that React will know to evaluate it as JavaScript.

分解对象后,可以使用各个数据。 在这种情况下,您将在<h2>标签中使用标题,并用花括号将值括起来,以便React可以将其评估为JavaScript。

You can also use a property on the prop object using dot notation. As an example, you could create an <h2> element like this: <h2>{props.title}</h2>. The advantage of destructring is that you can collect unused props and use the .

您还可以使用点表示法在prop对象上使用属性。 例如,您可以创建一个<h2>元素,如下所示: <h2>{props.title}</h2> 。 销毁的好处是您可以收集未使用的道具并使用 。

Save and exit the file. When you do, the browser will reload and you’ll see the specific name for each animal instead of a placeholder.

保存并退出文件。 完成后,浏览器将重新加载,您将看到每种动物的特定名称,而不是占位符。

The name property is a string, but props can be any data type that you could pass to a JavaScript function. To see this at work, add the rest of the data.

name属性是一个字符串,但是props可以是您可以传递给JavaScript函数的任何数据类型。 要查看此功能,请添加其余数据。

Open the App.js file:

打开App.js文件:

  • nano src/components/App/App.js

    纳米src / components / App / App.js

Add a prop for each of the following: scientificName, size, diet, and additional. These include strings, integers, arrays, and objects.

为以下各项添加一个道具: scientificNamesizedietadditional 。 这些包括字符串,整数,数组和对象。

prop-tutorial/src/components/App/App.js
prop-tutorial / src / components / App / App.js
import React from 'react';...function App() {  return (    

Animals

{albums.map(album => (
))}
)}export default App;

Since you are creating an object, you can add them in any order you want. Alphabetizing makes it easier to skim a list of props especially in a larger list. You also can add them on the same line, but separating to one per line keeps things readable.

由于正在创建对象,因此可以按所需的任何顺序添加它们。 按字母顺序排列可以更轻松地浏览道具列表,尤其是在较大列表中。 您也可以将它们添加在同一行上,但是每行分隔为一个可使内容可读。

Save and close the file. Open AnimalCard.js.

保存并关闭文件。 打开AnimalCard.js

  • nano src/components/AnimalCard/AnimalCard.js

    纳米src / components / AnimalCard / AnimalCard.js

This time, destructure the props in the function parameter list and use the data in the component:

这次,分解功能参数列表中的props并使用组件中的数据:

prop-tutorial/src/components/AnimalCard/AnimalCard.js
prop-tutorial / src / components / AnimalCard / AnimalCard.js
import React from 'react';import './AnimalCard.css'export default function AnimalCard({  additional,  diet,  name,  scientificName,  size}) {  return (    

{name}

{scientificName}

{size}kg

{diet.join(', ')}.
);}

After pulling out the data, you can add the scientificName and size into heading tags, but you’ll need to convert the array into a string so that React can display it on the page. You can do that with , which will create a comma separated list.

提取数据后,您可以将scientificNamesize添加到标题标签中,但是您需要将数组转换为字符串,以便React可以在页面上显示它。 您可以使用 ,这将创建一个逗号分隔的列表。

Save and close the file. When you do, the browser will refresh and you’ll see the structured data.

保存并关闭文件。 完成后,浏览器将刷新,您将看到结构化数据。

You could create a similar list with the additional object, but instead add a function to alert the user with the data. This will give you the chance to pass functions as props and then use data inside a component when you call a function.

您可以使用additional对象创建一个类似的列表,但是可以添加一个函数来用数据提醒用户。 这将使您有机会将函数作为道具传递,然后在调用函数时在组件内部使用数据。

Open App.js:

打开App.js

  • nano src/components/App/App.js

    纳米src / components / App / App.js

Create a function called showAdditionalData that will convert the object to a string and display it as an alert.

创建一个名为showAdditionalData的函数,该函数会将对象转换为字符串并将其显示为警报。

prop-tutorial/src/components/App/App.js
prop-tutorial / src / components / App / App.js
import React from 'react';...function showAdditional(additional) {  const alertInformation = Object.entries(additional)    .map(information => `${information[0]}: ${information[1]}`)    .join('\n');  alert(alertInformation)};function App() {  return (    

Animals

{data.map(animal => (
))}
)}export default App;

The function showAdditional converts the object to an array of pairs where the first item is the key and the second is the value. It then maps over the data converting the key-pair to a string. Then it joins them with a line break—\n—before passing the complete string to the alert function.

函数showAdditional将对象转换为成对的数组,其中第一项是键,第二项是值。 然后,它将数据映射到将密钥对转换为字符串的数据。 然后,在将完整的字符串传递给警报功能之前,它们以换行符( \n将它们连接起来。

Since JavaScript can accept functions as arguments, React can also accept functions as props. You can therefore pass showAdditional to AnimalCard as a prop called showAdditional.

由于JavaScript可以接受函数作为参数,因此React也可以接受函数作为道具。 因此,您可以通过showAdditionalAnimalCard一个名为道具showAdditional

Save and close the file. Open AnimalCard:

保存并关闭文件。 打开AnimalCard

  • nano src/components/AnimalCard/AnimalCard.js

    纳米src / components / AnimalCard / AnimalCard.js

Pull the showAdditional function from the props object, then create a <button> with an that calls the function with the additional object:

从props对象中showAdditional函数,然后创建一个带有的<button> ,该将使用additional对象调用该函数:

prop-tutorial/src/components/AnimalCard/AnimalCard.js
prop-tutorial / src / components / AnimalCard / AnimalCard.js
import React from 'react';import './AnimalCard.css'export default function AnimalCard({  additional,  diet,  name,  scientificName,  showAdditional,  size}) {  return (    

{name}

{scientificName}

{size}kg

{diet.join(', ')}.
);}

Save the file. When you do, the browser will refresh and you’ll see a button after each card. When you click the button, you’ll get an alert with the additional data.

保存文件。 完成后,浏览器将刷新,每张卡之后都会显示一个按钮。 单击按钮时,您将收到带有其他数据的警报。

If you try clicking More Info for the Lion, you will get an error. That’s because there is no additional data for the lion. You’ll see how to fix that in Step 3.

如果您尝试单击Lion 更多信息 ,则会出现错误。 那是因为没有关于狮子的其他数据。 您将在步骤3中看到如何解决该问题。

Finally, add some styling to the music card. Add a className of animal-wrapper to the div in AnimalCard:

最后,为音乐卡添加一些样式。 将animal-wrapperclassName添加到AnimalCard的div中:

prop-tutorial/src/components/AnimalCard/AnimalCard.js
prop-tutorial / src / components / AnimalCard / AnimalCard.js
import React from 'react';import './AnimalCard.css'export default function AnimalCard({...  return (    
...
)}

Save and close the file. Open AnimalCard.css:

保存并关闭文件。 打开AnimalCard.css

  • nano src/components/AnimalCard/AnimalCard.css

    纳米src / components / AnimalCard / AnimalCard.css

Add CSS to give the cards and the button a small border and padding:

添加CSS为卡片和按钮添加小边框和填充:

prop-tutorial/src/components/AnimalCard/AnimalCard.css
prop-tutorial / src / components / AnimalCard / AnimalCard.css
.animal-wrapper {    border: solid black 1px;    margin: 10px;    padding: 10px;    width: 200px;}.animal-wrapper button {    font-size: 1em;    border: solid black 1px;    padding: 10;    background: none;    cursor: pointer;    margin: 10px 0;}

This CSS will add a slight border to the card and replace the default button styling with a border and padding. cursor: pointer will change the cursor when you hover over the button.

该CSS会在卡片上添加一个轻微的边框,并用边框和填充替换默认的按钮样式。 cursor: pointer将鼠标悬停在按钮上时, cursor: pointer将更改光标。

Save and close the file. When you do the browser will refresh and you’ll see the data in individual cards.

保存并关闭文件。 完成后,浏览器将刷新,您将在单个卡中看到数据。

At this point, you’ve created two custom components. You’ve passed data to the second component from the first component using props. The props included a variety of data, such as strings, integers, arrays, objects, and functions. In your second component, you used the props to create a dynamic component using JSX.

至此,您已经创建了两个自定义组件。 您已使用道具将数据从第一个组件传递到第二个组件。 道具包含各种数据,例如字符串,整数,数组,对象和函数。 在第二个组件中,您使用道具使用JSX创建了一个动态组件。

In the next step, you’ll use a type system called prop-types to specify the structure your component expects to see, which will create predictability in your app and prevent bugs.

在下一步中,您将使用称为prop-types的类型系统来指定组件希望看到的结构,这将在您的应用程序中创建可预测性并防止错误。

步骤3 —使用PropTypesdefaultProps创建可预测的道具 (Step 3 — Creating Predictable Props with PropTypes and defaultProps)

In this step, you’ll add a light type system to your components with PropTypes. PropTypes act like other type systems by explicitly defining the type of data you expect to receive for a certain prop. They also give you the chance to define default data in cases where the prop is not always required. Unlike most type systems, PropTypes is a runtime check, so if the props do not match the type the code will still compile, but will also display a console error.

在此步骤中,您将使用PropTypes将灯光类型系统添加到组件中。 PropTypes像其他类型系统一样,通过显式定义您希望为特定道具接收的数据类型来工作。 在并非总是需要prop的情况下,它们还使您有机会定义默认数据。 与大多数类型系统不同, PropTypes是运行时检查,因此,如果props与类型不匹配,则代码仍会编译,但也会显示控制台错误。

By the end of this step, you’ll add predictability to your custom component by defining the type for each prop. This will ensure that the next person to work on the component will have a clear idea of the structure of the data the component will need.

在此步骤结束时,您将通过定义每个道具的类型来增加自定义组件的可预测性。 这将确保下一位从事组件工作的人员对组件所需的数据结构有清晰的了解。

The prop-types package is included as part of the Create React App installation, so to use it, all you have to do is import it into your component.

prop-types包包含在Create React App安装中,因此,要使用它,只需将其导入到组件中即可。

Open up AnimalCard.js:

打开AnimalCard.js

  • nano src/components/AnimalCard/AnimalCard.js

    纳米src / components / AnimalCard / AnimalCard.js

Then import PropTypes from prop-types:

然后从prop-types导入PropTypes

prop-tutorial/src/components/AnimalCard/AnimalCard.js
prop-tutorial / src / components / AnimalCard / AnimalCard.js
import React from 'react';import PropTypes from 'prop-types';import './AnimalCard.css'export default function AnimalCard({...}

Add PropTypes directly to the component function. In JavaScript, , which means you can add properties using dot syntax. Add the following PropTypes to AnimalCard.js:

PropTypes直接添加到组件函数。 在JavaScript中, ,这意味着您可以使用点语法添加属性。 将以下PropTypes添加到AnimalCard.js

prop-tutorial/src/components/AnimalCard/AnimalCard.js
prop-tutorial / src / components / AnimalCard / AnimalCard.js
import React from 'react';import PropTypes from 'prop-types';import './AnimalCard.css'export default function AnimalCard({...}AnimalCard.propTypes = {  additional: PropTypes.shape({    link: PropTypes.string,    notes: PropTypes.string  }),  diet: PropTypes.arrayOf(PropTypes.string).isRequired,  name: PropTypes.string.isRequired,  scientificName: PropTypes.string.isRequired,  showAdditional: PropTypes.func.isRequired,  size: PropTypes.number.isRequired,}

Save and close the file.

保存并关闭文件。

As you can see, there are many different PropTypes. This is only a small sample; see the to see the others you can use.

如您所见,有许多不同的PropTypes 。 这只是一个小样本; 查看以查看其他可以使用的 。

Let’s start with the name prop. Here, you are specifying that name must be a string. The property scientificName is the same. size is a number, which can include both floats such as 1.5 and integers such as 6. showAdditional is a function (func).

让我们从prop这个name开始。 在这里,您指定name必须是string 。 属性scientificName是相同的。 size是一个number ,可以包含浮点数(例如1.5和整数(例如6showAdditional是一个函数( func )。

diet, on the other hand, is a little different. In this case, you are specifying that diet will be an array, but you also need to specify what this array will contain. In this case, the array will only contain strings. If you want to mix types, you can use another prop called oneOfType, which takes an array of valid PropTypes. You can use oneOfType anywhere, so if you wanted size to be either a number or a string you could change it to this:

另一方面, diet略有不同。 在这种情况下,您要指定diet将是一个array ,但还需要指定此数组将包含的内容。 在这种情况下,数组将仅包含字符串。 如果要混合类型,则可以使用另一个名为oneOfType道具,该道具采用有效的PropTypes数组。 您可以在任何地方使用oneOfType ,因此,如果您希望size为数字或字符串,则可以将其更改为:

size: PropTypes.oneOfType([PropTypes.number, PropTypes.string])

The prop additional is also a little more complex. In this case, you are specifying an object, but to be a little more clear, you are stating what you want the object to contain. To do that, you use PropTypes.shape, which takes an object with additional fields that will need their own PropTypes. In this case, link and notes are both PropTypes.string.

additional的道具也有些复杂。 在这种情况下,您要指定一个对象,但为了更加清楚一点,您要说明该对象要包含的内容。 为此,您可以使用PropTypes.shape ,该对象带有一个带有其他字段的对象,这些字段需要自己的PropTypes 。 在这种情况下, linknotes都是PropTypes.string

Currently, all of the data is well-formed and matches the props. To see what happens if the PropTypes don’t match, open up your data:

目前,所有数据的格式都正确并且与道具匹配。 要查看PropTypes不匹配会发生什么,请打开数据:

  • nano src/components/App/data.js

    纳米src / components / App / data.js

Change the size to a string on the first item:

在第一项上将大小更改为字符串:

prop-tutorial/src/components/App/data.js
prop-tutorial / src / components / App / data.js
export default [  {    name: 'Lion',    scientificName: 'Panthero leo',    size: '140',    diet: ['meat'],  },...]

Save the file. When you do the browser will refresh and you’ll see an error in the console.

保存文件。 完成后,浏览器将刷新,并且您会在控制台中看到错误。

Error   
index.js:1 Warning: Failed prop type: Invalid prop `size` of type `string` supplied to `AnimalCard`, expected `number`. in AnimalCard (at App.js:18) in App (at src/index.js:9) in StrictMode (at src/index.js:8)

Unlike other type systems such as , PropTypes will not give you a warning at build time, and as long as there are no code errors, it will still compile. This means that you could accidentally publish code with prop errors.

与诸如类的其他类型系统不同, PropTypes时不会向您发出警告,并且只要没有代码错误,它仍然可以编译。 这意味着您可能会意外发布带有属性错误的代码。

Change the data back to the correct type:

将数据更改回正确的类型:

prop-tutorial/src/components/App/data.js
prop-tutorial / src / components / App / data.js
export default [  {    name: 'Lion',    scientificName: 'Panthero leo',    size: 140,    diet: ['meat'],  },...]

Save and close the file.

保存并关闭文件。

Open up AnimalCard.js:

打开AnimalCard.js

  • nano src/components/AnimalCard/AnimalCard.js

    纳米src / components / AnimalCard / AnimalCard.js

Every prop except for additional has the isRequired property. That means, that they are required. If you don’t include a required prop, the code will still compile, but you’ll see a runtime error in the console.

additional属性外,每个道具都具有isRequired属性。 这意味着它们是必需的。 如果不包括必需的prop,则代码仍会编译,但是您会在控制台中看到运行时错误。

If a prop isn’t required, you can add a default value. It’s good practice to always add a default value to prevent runtime errors if a prop is not required. For example, in the AnimalCard component, you are calling a function with the additional data. If it’s not there, the function will try and modify an object that doesn’t exist and the application will crash.

如果不需要道具,则可以添加默认值。 优良作法是始终添加默认值,以防止在不需要属性时出现运行时错误。 例如,在AnimalCard组件中,您正在使用additional数据调用函数。 如果不存在,该函数将尝试修改不存在的对象,应用程序将崩溃。

To prevent this problem, add a defaultProp for additional:

为避免此问题,请为additional添加一个defaultProp

prop-tutorial/src/components/AnimalCard/AnimalCard.js
prop-tutorial / src / components / AnimalCard / AnimalCard.js
import React from 'react';import PropTypes from 'prop-types';import './AnimalCard.css'export default function AnimalCard({...}AnimalCard.propTypes = {  additional: PropTypes.shape({    link: PropTypes.string,    notes: PropTypes.string  }),...}AnimalCard.defaultProps = {  additional: {    notes: 'No Additional Information'  }}

You add the defaultProps to the function using dot syntax just as you did with propTypes, then you add a default value that the component should use if the prop is undefined. In this case, you are matching the shape of additional, including a message that the there is no additional information.

就像使用propTypes ,使用点语法将defaultProps添加到函数中,然后添加默认值,如果prop undefined ,则组件应使用该默认值。 在这种情况下,你是匹配的形状additional ,包括一条消息,该不存在附加信息。

Save and close the file. When you do, the browser will refresh. After it refreshes, click on the More Info button for Lion. It has no additional field in the data so the prop is undefined. But AnimalCard will substitute in the default prop.

保存并关闭文件。 完成后,浏览器将刷新。 刷新后,单击Lion的“ 更多信息”按钮。 它在数据中没有additional字段,因此prop是undefined 。 但是AnimalCard将替代默认道具。

Now your props are well-documented and are either required or have a default to ensure predictable code. This will help future developers (including yourself) understand what props a component needs. It will make it easier to swap and reuse your components by giving you full information about how the component will use the data it is receiving.

现在,您的道具已被详细记录,并且是必需的或具有默认值以确保代码可预测。 这将帮助未来的开发人员(包括您自己)了解组件需要什么道具。 通过为您提供有关组件将如何使用其接收的数据的完整信息,它将使交换和重用组件变得更加容易。

结论 (Conclusion)

In this tutorial, you have created several components that use props to display information from a parent. Props give you the flexibility to begin to break larger components into smaller, more focused pieces. Now that you no longer have your data tightly coupled with your display information, you have the ability to make choices about how to segment your application.

在本教程中,您创建了几个组件,这些组件使用道具来显示来自父级的信息。 道具使您可以灵活地将较大的组件分解为更小,更集中的部分。 现在,您不再需要将数据与显示信息紧密结合在一起,就可以选择如何对应用程序进行细分。

Props are a crucial tool in building complex applications, giving the opportunity to create components that can adapt to the data they receive. With PropTypes, you are creating predictable and readable components that will give a team the ability to reuse each other’s work to create a flexible and stable code base. If you would like to look at more React tutorials, take a look at our , or return to the .

道具是构建复杂应用程序的关键工具,使您有机会创建可以适应其接收到的数据的组件。 使用PropTypes ,您将创建可预测且可读的组件,这将使团队能够重用彼此的工作来创建灵活而稳定的代码库。 如果您更多的React教程,请看一下我们的 ,或者回到的 。

翻译自:

react 组件中使用组件

转载地址:http://umhgb.baihongyu.com/

你可能感兴趣的文章
Laravel 的生命周期
查看>>
CentOS Docker 安装
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
【2020-3-21】Mac安装Homebrew慢,解决办法
查看>>
influxdb 命令行输出时间为 yyyy-MM-dd HH:mm:ss(年月日时分秒)的方法
查看>>
Docker(一)使用阿里云容器镜像服务
查看>>
FFmpeg 新旧版本编码 API 的区别
查看>>
RecyclerView 源码深入解析——绘制流程、缓存机制、动画等
查看>>
Android 面试题整理总结(一)Java 基础
查看>>
Android 面试题整理总结(二)Java 集合
查看>>
学习笔记_vnpy实战培训day02
查看>>
学习笔记_vnpy实战培训day03
查看>>
VNPY- VnTrader基本使用
查看>>
VNPY - CTA策略模块策略开发
查看>>
VNPY - 事件引擎
查看>>
MongoDB基本语法和操作入门
查看>>
学习笔记_vnpy实战培训day04_作业
查看>>
OCO订单(委托)
查看>>