Skip to main content

属性

大多数组件在创建时都可以使用不同的参数进行自定义。这些创建的参数称为 props,是属性的缩写。

¥Most components can be customized when they are created, with different parameters. These created parameters are called props, short for properties.

例如,一个基本的 React Native 组件是 Image。创建图片时,可以使用名为 source 的 prop 来控制它显示的图片。

¥For example, one basic React Native component is the Image. When you create an image, you can use a prop named source to control what image it shows.

注意 {pic} 周围的大括号 - 这些将变量 pic 嵌入到 JSX 中。你可以将任何 JavaScript 表达式放在 JSX 中的大括号内。

¥Notice the braces surrounding {pic} - these embed the variable pic into JSX. You can put any JavaScript expression inside braces in JSX.

你自己的组件也可以使用 props。这使你可以创建一个在应用中的许多不同位置使用的单个组件,通过在 render 函数中引用 props,每个位置的属性略有不同。这是一个例子:

¥Your own components can also use props. This lets you make a single component that is used in many different places in your app, with slightly different properties in each place by referring to props in your render function. Here's an example:

使用 name 作为 prop 可以让我们自定义 Greeting 组件,这样我们就可以为每个问候语重用该组件。此示例也使用了 JSX 中的 Greeting 组件,与 核心组件 类似。React 如此酷的原因就在于它的强大功能 - 如果你发现自己希望有一组不同的 UI 原语可供使用,你可以发明新的。

¥Using name as a prop lets us customize the Greeting component, so we can reuse that component for each of our greetings. This example also uses the Greeting component in JSX, similar to the Core Components. The power to do this is what makes React so cool - if you find yourself wishing that you had a different set of UI primitives to work with, you can invent new ones.

这里发生的另一个新事物是 View 组件。View 可用作其他组件的容器,以帮助控制样式和布局。

¥The other new thing going on here is the View component. A View is useful as a container for other components, to help control style and layout.

使用 props 和基本的 TextImageView 组件,你可以构建各种静态屏幕。要了解如何使你的应用随时间变化,你需要 了解状态

¥With props and the basic Text, Image, and View components, you can build a wide variety of static screens. To learn how to make your app change over time, you need to learn about State.