首页 > 其他分享 >React props 用法

React props 用法

时间:2023-07-04 09:13:00浏览次数:60  
标签:function return component 用法 React components props

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components. You can find a detailed component API reference here.

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

Function and Class Components

The simplest way to define a component is to write a JavaScript function:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.

You can also use an ES6 class to define a component:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

The above two components are equivalent from React’s point of view.

Function and Class components both have some additional features that we will discuss in the next sections.

Rendering a Component

Previously, we only encountered React elements that represent DOM tags:

const element = <div />;

However, elements can also represent user-defined components:

const element = <Welcome name="Sara" />;

When React sees an element representing a user-defined component, it passes JSX attributes and children to this component as a single object. We call this object “props”.

For example, this code renders “Hello, Sara” on the page:

function Welcome(props) {  return <h1>Hello, {props.name}</h1>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />;root.render(element);

Try it on CodePen

Let’s recap what happens in this example:

  1. We call root.render() with the <Welcome name="Sara" /> element.
  2. React calls the Welcome component with {name: 'Sara'} as the props.
  3. Our Welcome component returns a <h1>Hello, Sara</h1> element as the result.
  4. React DOM efficiently updates the DOM to match <h1>Hello, Sara</h1>.

Note: Always start component names with a capital letter.

React treats components starting with lowercase letters as DOM tags. For example, <div /> represents an HTML div tag, but <Welcome /> represents a component and requires Welcome to be in scope.

To learn more about the reasoning behind this convention, please read JSX In Depth.

Composing Components

Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.

For example, we can create an App component that renders Welcome many times:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />      <Welcome name="Cahal" />      <Welcome name="Edite" />    </div>
  );
}

Try it on CodePen

Typically, new React apps have a single App component at the very top. However, if you integrate React into an existing app, you might start bottom-up with a small component like Button and gradually work your way to the top of the view hierarchy.

Extracting Components

Don’t be afraid to split components into smaller components.

For example, consider this Comment component:

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Try it on CodePen

It accepts author (an object), text (a string), and date (a date) as props, and describes a comment on a social media website.

This component can be tricky to change because of all the nesting, and it is also hard to reuse individual parts of it. Let’s extract a few components from it.

First, we will extract Avatar:

function Avatar(props) {
  return (
    <img className="Avatar"      src={props.user.avatarUrl}      alt={props.user.name}    />  );
}

The Avatar doesn’t need to know that it is being rendered inside a Comment. This is why we have given its prop a more generic name: user rather than author.

We recommend naming props from the component’s own point of view rather than the context in which it is being used.

We can now simplify Comment a tiny bit:

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <Avatar user={props.author} />        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Next, we will extract a UserInfo component that renders an Avatar next to the user’s name:

function UserInfo(props) {
  return (
    <div className="UserInfo">      <Avatar user={props.user} />      <div className="UserInfo-name">        {props.user.name}      </div>    </div>  );
}

This lets us simplify Comment even further:

function Comment(props) {
  return (
    <div className="Comment">
      <UserInfo user={props.author} />      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Try it on CodePen

Extracting components might seem like grunt work at first, but having a palette of reusable components pays off in larger apps. A good rule of thumb is that if a part of your UI is used several times (ButtonPanelAvatar), or is complex enough on its own (AppFeedStoryComment), it is a good candidate to be extracted to a separate component.

Props are Read-Only

Whether you declare a component as a function or a class, it must never modify its own props. Consider this sum function:

function sum(a, b) {
  return a + b;
}

Such functions are called “pure” because they do not attempt to change their inputs, and always return the same result for the same inputs.

In contrast, this function is impure because it changes its own input:

function withdraw(account, amount) {
  account.total -= amount;
}

React is pretty flexible but it has a single strict rule:

All React components must act like pure functions with respect to their props.

Of course, application UIs are dynamic and change over time. In the next section, we will introduce a new concept of “state”. State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.

标签:function,return,component,用法,React,components,props
From: https://www.cnblogs.com/weifeng1463/p/17524753.html

相关文章

  • linux grep基本用法--九五小庞
    通过此语句可以查询一个文件或者当前目录下所有文件中包含exception和error的文件grep-E-i"((exception)|(error))"*1.查找文件中是否存在指定的信息:grep<查找信息><文件名>-bash-4.1$grepexceptionerror-2015-12-29.log17:49:13.869[http-/192.168.0.80:8080-12]......
  • ASP.NET Core 6框架揭秘实例演示[41]:跨域资源的共享(CORS)N种用法
    同源策略是所有浏览器都必须遵循的一项安全原则,它的存在决定了浏览器在默认情况下无法对跨域请求的资源做进一步处理。为了实现跨域资源的共享,W3C制定了CORS规范。ASP.NET利用CorsMiddleware中间件提供了针对CORS规范的实现。(本文提供的示例演示已经同步到《ASP.NETCore6框架揭......
  • 39.volatile、mutable和explicit关键字的用法
    39.volatile、mutable和explicit关键字的用法1.volatile☀警告volatile的确切含义与机器有关,只能通过阅读编译器文档来理解。要想让使用了volatile的程序在移植到新机器或新编译器后仍然有效,通常需要对该程序进行某些改变。直接处理硬件的程序常常包含这样的数据元素,它们的值......
  • 30.externC的用法
    为了能够正确地在C++代码中调用C语言的代码:在程序中加上extern"C"后,相当于告诉编译器这部分代码是C语言写的,因此要按照C语言进行编译,而不是C++;哪些情况下使用extern"C":(1)C++代码中调用C语言代码;(2)在C++中的头文件中使用;(3)在多个人协同开发时,可能有人擅长C语言,而有人擅长C++;举......
  • MYSQL笔记:删除操作Delete、Truncate、Drop用法比较
    1、执行速度比较Delete、Truncate、Drop关键字都可以删除数据drop>truncate>delete2、原理方面2.1deletedelete属于数据库DML操作语言,只会删除数据表中的记录,会执行事务,执行的时候也会触发触发器。InnoDB数据库引擎中,执行delete操作只会给删除的记录打上了删除标记,并不会真正删除......
  • How to use handleChange() function in react component?
    An onChange eventistriggeredwhenvaluesareenteredintheinput.Thisfiresafunction handleChange(),thatisusedtosetanewstatefortheinput.1.HandlingSingleInputFirst,wehavetosetuptheinputfieldasacontrolledcomponentsothatw......
  • React hooks
    什么是ReactHook?hook(钩子)是一种特殊的函数,它允许你“钩入”各种React特性。假设一个函数返回一个有两个值的数组:第一个值: 一个带有状态state的变量。第二个值: 一个带有处理程序handle(改变当前状态的函数)的变量。就是这样,很简单。......
  • react之自定义hooks
    原文合集地址如下,有需要的朋友可以关注本文地址合集地址任何相对独立、复用性强的逻辑,都可以extract为自定义Hook,自定义Hook是一种复用React的状态逻辑的函数。自定义Hook的主要特点是:抽象组件间的状态逻辑,方便复用让功能组件更纯粹,更易于维护自定义Hook可......
  • react-native项目启动报错 Error: `fsevents` unavailable (this watcher can only be
    react-native项目启动报错——watchman安装问题(macpro) LookingforJSfilesin/Users/你的名称/Documents/project/文件夹名Loadingdependencygraph.../Users/你的名称/Documents/project/文件夹名/node_modules/metro/node_modules/sane/src/fsevents_watcher.js:37......
  • Oracle Case 用法及注意事项
    OracleCase两种用法:注意事项:在条件中一定要增加其他条件的处理或者默认值,否则遇到未包含条件会抛异常>在条件中一定要增加其他条件的处理或者默认值,否则遇到未包含条件会抛异常1.查询语句语法:selectcasefieldnamewhenexp1thenresult1whenexp2thenresult2e......