1658523600
在本文中,我们将介绍 React 的 HOC 概念的基础知识,包括向您介绍高阶组件、教您语法以及向您展示如何应用 HOC。我们还将讨论一些您在使用高阶组件时可能遇到的常见问题。
假设用户想要一个在每个onClick
事件上增加一个计数器变量的组件:
function ClickCounter() {
const [count, setCount] = useState(0); //default value of this state will be 0.
return (
<div>
{/*When clicked, increment the value of 'count'*/}
<button onClick={() => setCount((count) => count + 1)}>Increment</button>
<p>Clicked: {count}</p> {/*Render the value of count*/}
</div>
);
}
export default ClickCounter;
我们的代码有效!但是,考虑这种情况:如果客户端想要另一个包含相同功能的组件,但它会触发一个onMouseOver
事件怎么办?
为了使这成为可能,我们必须编写以下代码:
function HoverCounter(props) {
const [count, setCount] = useState(0);
return (
<div>
{/*If the user hovers over this button, then increment 'count'*/}
<button onMouseOver={() => setCount((count) => count + 1)}>
Increment
</button>
<p>
Clicked: {count}
</p>
</div>
);
}
export default HoverCounter;
尽管我们的代码示例是有效的,但存在一个主要问题:两个文件具有相似的代码逻辑。
因此,这打破了DRY 概念。那么我们如何解决这个问题呢?
这就是 HOC 的用武之地。在这里,高阶组件允许开发人员在他们的项目中重用代码逻辑。因此,这意味着更少的重复和更优化、更易读的代码。
现在我们已经介绍了它的优势,让我们开始使用 HOC!
根据React 的文档,一个典型的 React HOC 有如下定义:
高阶组件是一个接收组件并返回新组件的函数。
使用代码,我们可以像这样重写上面的语句:
const newComponent = higherFunction(WrappedComponent);
在这一行:
newComponent
— 将是增强组件higherFunction
——顾名思义,这个功能将增强WrappedComponent
WrappedComponent
— 我们想要扩展其功能的组件。换句话说,这将是我们想要增强的组件在本文的下一部分中,我们将看到 React 的 HOC 概念的实际应用。
在编写一些代码之前,我们必须先创建一个空白的 React 项目。为此,首先编写以下代码:
npx create-react-app hoc-tutorial
cd hoc-tutorial #navigate to the project folder.
cd src #go to codebase
mkdir components #will hold all our custom components
对于本文,我们将构建两个自定义组件来演示 HOC 的使用:
ClickIncrease.js
— 该组件将呈现一个按钮和一段文本。当用户点击这个按钮(一个onClick
事件)时,fontSize
文本的属性会增加HoverIncrease.js
— 将类似于ClickIncrease
。然而,与前者不同的是,这个组件会监听onMouseOver
事件在您的项目中,导航到该components
文件夹。在这里,创建这两个新文件。
完成后,您的文件结构应如下所示:
现在我们已经为项目奠定了基础,是时候构建我们的自定义组件了。
在ClickIncrease.js
中,首先编写以下代码:
//file name: components/ClickIncrease.js
function ClickIncrease() {
const [fontSize, setFontSize] = useState(10); //set initial value of Hook to 10.
return (
<div>
{/*When clicked, increment the value of fontSize*/}
<button onClick={() => setFontSize((size) => size + 1)}>
Increase with click
</button>
{/*Set the font size of this text to the fontSize variable.*/}
{/*Furthermore, display its value as well.*/}
<p style={{ fontSize }}>Size of font in onClick function: {fontSize}</p>
</div>
);
}
export default ClickIncrease;
接下来,在您的HoverIncrease
组件中,粘贴以下代码行:
function HoverIncrease(props) {
const [fontSize, setFontSize] = useState(10);
return (
<div>
{/*This time, instead of listening to clicks,*/}
{/*Listen to hover events instead*/}
<button onMouseOver={() => setFontSize((size) => size + 1)}>
Increase on hover
</button>
<p style={{ fontSize }}>
Size of font in onMouseOver function: {fontSize}
</p>
</div>
);
}
export default HoverIncrease;
最后,将这些函数渲染到 GUI,如下所示:
//import both components
import ClickIncrease from "./components/ClickIncrease";
import HoverIncrease from "./components/HoverIncrease";
export default function App() {
return (
<div className="App">
{/*Render both of these components to the UI */}
<ClickIncrease />
<HoverIncrease />
</div>
);
}
让我们测试一下!这将是代码的结果:
在components
文件夹中,创建一个名为withCounter.js
. 在这里,首先编写以下代码:
import React from "react";
const UpdatedComponent = (OriginalComponent) => {
function NewComponent(props) {
//render OriginalComponent and pass on its props.
return <OriginalComponent />;
}
return NewComponent;
};
export default UpdatedComponent;
让我们逐段解构这段代码:
UpdatedComponent
,它接受一个名为 的参数OriginalComponent
。在这种情况下,OriginalComponent
将是将被包装的 React 元素OriginalComponent
到 UI。我们将在本文后面实现增强功能完成后,就可以UpdatedComponent
在我们的应用程序中使用该功能了。
为此,首先转到HoverIncrease.js
文件并编写以下行:
import withCounter from "./withCounter.js" //import the withCounter function
//..further code ..
function HoverIncrease() {
//..further code
}
//replace your 'export' statement with:
export default withCounter(HoverIncrease);
//We have now converted HoverIncrease to an HOC function.
接下来,对ClickIncrease
模块执行相同的过程:
//file name: components/ClickIncrease.js
import withCounter from "./withCounter";
function ClickIncrease() {
//...further code
}
export default withCounter(ClickIncrease);
//ClickIncrease is now a wrapped component of the withCounter method.
让我们测试一下!这将是代码中的结果:
请注意,我们的结果没有改变。这是因为我们还没有对我们的 HOC 进行更改。在下一小节中,您将学习如何在我们的组件之间共享道具。
通过 HOC,React 允许用户在项目的包装组件中共享道具。
第一步,像这样创建一个name
道具withCounter.js
:
//file name: components/withCounter.js
const UpdatedComponent = (OriginalComponent) => {
function NewComponent(props) {
//Here, add a 'name' prop and set its value of 'LogRocket'.
return <OriginalComponent name="LogRocket" />;
}
//..further code..
而已!要读取这个数据道具,我们要做的就是对其子组件进行以下更改:
//extra code removed for brevity.
//In components/HoverIncrease
function HoverIncrease(props) { //get the shared props
return (
<div>
{/* Further code..*/}
{/*Now render the value of the 'name' prop */ }
<p> Value of 'name' in HoverIncrease: {props.name}</p>
</div>
);
}
//Now In components/ClickIncrease.js
function ClickIncrease(props) {
//accept incoming props
return (
<div>
{/*Further code..*/}
<p>Value of 'name' in ClickIncrease: {props.name}</p>
</div>
);
}
那很简单!如您所见,React 的 HOC 设计允许开发人员相对轻松地在组件之间共享数据。
在接下来的部分中,您现在将学习如何通过 HOC 函数共享状态。
就像 props 一样,我们甚至可以共享 Hooks:
//In components/withCounter.js
const UpdatedComponent = (OriginalComponent) => {
function NewComponent(props) {
const [counter, setCounter] = useState(10); //create a Hook
return (
<OriginalComponent
counter={counter} //export our counter Hook
//now create an 'incrementSize' function
incrementCounter={() => setCounter((counter) => counter + 1)}
/>
);
}
//further code..
下面是对代码的解释:
counter
并将其初始值设置为10
incrementCounter
函数。调用时,此方法将增加counter
incrementSize
方法和size
Hook 导出为道具。因此,这允许被包装的组件UpdatedComponent
访问这些 Hook作为最后一步,我们现在必须使用counter
Hook。
为此,请在HoverIncrease
andClickIncrease
模块中编写以下代码行:
//make the following file changes to components/HoverIncrease.js and ClickIncrease.js
//extract the counter Hook and incrementCounter function from our HOC:
const { counter, incrementCounter } = props;
return (
<div>
{/*Use the incrementCounter method to increment the 'counter' state..*/}
<button onClick={() => incrementCounter()}>Increment counter</button>
{/*Render the value of our 'counter' variable:*/}
<p> Value of 'counter' in HoverIncrease/ClickIncrease: {counter}</p>
</div>
);
在这里,需要注意的一件重要事情是counter
状态的值不会在我们的子组件之间共享。如果你想在各种 React 组件之间共享状态,请使用React 的 Context API,它可以让你轻松地在整个应用程序中共享状态和 Hooks。
即使我们的代码可以工作,请考虑以下情况:如果我们想counter
使用自定义值增加 的值怎么办?通过 HOC,我们甚至可以告诉 React 将特定数据传递给某些子组件。这可以通过参数实现。
要启用对参数的支持,请在中编写以下代码components/withCounter.js
:
//This function will now accept an 'increaseCount' parameter.
const UpdatedComponent = (OriginalComponent, increaseCount) => {
function NewComponent(props) {
return (
<OriginalComponent
//this time, increment the 'size' variable by 'increaseCount'
incrementCounter={() => setCounter((size) => size + increaseCount)}
/>
);
//further code..
在这段代码中,我们通知 React 我们的函数现在将接收一个名为 的附加参数increaseCount
。
剩下的就是在我们包装的组件中使用这个参数。为此,在HoverIncrease.js
and中添加这行代码ClickIncrease.js
:
//In HoverIncrease, change the 'export' statement:
export default withCounter(HoverIncrease, 10); //value of increaseCount is 10.
//this will increment the 'counter' Hook by 10.
//In ClickIncrease:
export default withCounter(ClickIncrease, 3); //value of increaseCount is 3.
//will increment the 'counter' state by 3 steps.
最后,该withCounter.js
文件应如下所示:
import React from "react";
import { useState } from "react";
const UpdatedComponent = (OriginalComponent, increaseCount) => {
function NewComponent(props) {
const [counter, setCounter] = useState(10);
return (
<OriginalComponent
name="LogRocket"
counter={counter}
incrementCounter={() => setCounter((size) => size + increaseCount)}
/>
);
}
return NewComponent;
};
export default UpdatedComponent;
此外,HoverIncrease.js
应该是这样的:
import { useState } from "react";
import withCounter from "./withCounter";
function HoverIncrease(props) {
const [fontSize, setFontSize] = useState(10);
const { counter, incrementCounter } = props;
return (
<div>
<button onMouseOver={() => setFontSize((size) => size + 1)}>
Increase on hover
</button>
<p style={{ fontSize }}>
Size of font in onMouseOver function: {fontSize}
</p>
<p> Value of 'name' in HoverIncrease: {props.name}</p>
<button onClick={() => incrementCounter()}>Increment counter</button>
<p> Value of 'counter' in HoverIncrease: {counter}</p>
</div>
);
}
export default withCounter(HoverIncrease, 10);
最后,您的ClickIncrease
组件应该具有以下代码:
import { useEffect, useState } from "react";
import withCounter from "./withCounter";
function ClickIncrease(props) {
const { counter, incrementCounter } = props;
const [fontSize, setFontSize] = useState(10);
return (
<div>
<button onClick={() => setFontSize((size) => size + 1)}>
Increase with click
</button>
<p style={{ fontSize }}>Size of font in onClick function: {fontSize}</p>
<p>Value of 'name' in ClickIncrease: {props.name}</p>
<button onClick={() => incrementCounter()}>Increment counter</button>
<p> Value of 'counter' in ClickIncrease: {counter}</p>
</div>
);
}
export default withCounter(ClickIncrease, 3);
需要注意的重要一点是,将 props 传递给 HOC 的子组件的过程与非 HOC 组件的过程不同。
例如,看下面的代码:
function App() {
return (
<div>
{/*Pass in a 'secretWord' prop*/}
<HoverIncrease secretWord={"pineapple"} />
</div>
);
}
function HoverIncrease(props) {
//read prop value:
console.log("Value of secretWord: " + props.secretWord);
//further code..
}
理论上,我们应该Value of secretWord: pineapple
在控制台中得到消息。但是,这里不是这种情况:
那么这里发生了什么?
在这种情况下,secretWord
prop 实际上是传递给withCounter
函数而不是HoverIncrease
组件。
为了解决这个问题,我们必须做一个简单的改变withCounter.js
:
const UpdatedComponent = (OriginalComponent, increaseCount) => {
function NewComponent(props) {
return (
<OriginalComponent
//Pass down all incoming props to the HOC's children:
{...props}
/>
);
}
return NewComponent;
};
这个小修复解决了我们的问题:
我们完成了!
在本文中,您了解了 React 的 HOC 概念的基础知识。如果您在本文中遇到任何困难,我给您的建议是解构并使用上面的代码示例。这将帮助您更好地理解这个概念。
非常感谢您的阅读!快乐编码!
来源:https ://blog.logrocket.com/understanding-react-higher-order-components/
1598839687
If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?
In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.
Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.
React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.
Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.
Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.
The popularity of React Native comes from its advantages. Some of its advantages are as follows:
Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.
React Native is very close to native. Consider the following aspects as described on the React Native website:
Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.
#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native
1615544450
Since March 2020 reached 556 million monthly downloads have increased, It shows that React JS has been steadily growing. React.js also provides a desirable amount of pliancy and efficiency for developing innovative solutions with interactive user interfaces. It’s no surprise that an increasing number of businesses are adopting this technology. How do you select and recruit React.js developers who will propel your project forward? How much does a React developer make? We’ll bring you here all the details you need.
Facebook built and maintains React.js, an open-source JavaScript library for designing development tools. React.js is used to create single-page applications (SPAs) that can be used in conjunction with React Native to develop native cross-platform apps.
In the United States, the average React developer salary is $94,205 a year, or $30-$48 per hour, This is one of the highest among JavaScript developers. The starting salary for junior React.js developers is $60,510 per year, rising to $112,480 for senior roles.
In context of software developer wage rates, the United States continues to lead. In high-tech cities like San Francisco and New York, average React developer salaries will hit $98K and $114per year, overall.
However, the need for React.js and React Native developer is outpacing local labour markets. As a result, many businesses have difficulty locating and recruiting them locally.
It’s no surprise that for US and European companies looking for professional and budget engineers, offshore regions like India are becoming especially interesting. This area has a large number of app development companies, a good rate with quality, and a good pool of React.js front-end developers.
As per Linkedin, the country’s IT industry employs over a million React specialists. Furthermore, for the same or less money than hiring a React.js programmer locally, you may recruit someone with much expertise and a broader technical stack.
React is a very strong framework. React.js makes use of a powerful synchronization method known as Virtual DOM, which compares the current page architecture to the expected page architecture and updates the appropriate components as long as the user input.
React is scalable. it utilises a single language, For server-client side, and mobile platform.
React is steady.React.js is completely adaptable, which means it seldom, if ever, updates the user interface. This enables legacy projects to be updated to the most new edition of React.js without having to change the codebase or make a few small changes.
React is adaptable. It can be conveniently paired with various state administrators (e.g., Redux, Flux, Alt or Reflux) and can be used to implement a number of architectural patterns.
Is there a market for React.js programmers?
The need for React.js developers is rising at an unparalleled rate. React.js is currently used by over one million websites around the world. React is used by Fortune 400+ businesses and popular companies such as Facebook, Twitter, Glassdoor and Cloudflare.
As you’ve seen, locating and Hire React js Developer and Hire React Native developer is a difficult challenge. You will have less challenges selecting the correct fit for your projects if you identify growing offshore locations (e.g. India) and take into consideration the details above.
If you want to make this process easier, You can visit our website for more, or else to write a email, we’ll help you to finding top rated React.js and React Native developers easier and with strives to create this operation
#hire-react-js-developer #hire-react-native-developer #react #react-native #react-js #hire-react-js-programmer
1651604400
React Starter Kit is an opinionated boilerplate for web development built on top of Node.js, Express, GraphQL and React, containing modern web development tools such as Webpack, Babel and Browsersync. Helping you to stay productive following the best practices. A solid starting point for both professionals and newcomers to the industry.
See getting started guide, demo, docs, roadmap | Join #react-starter-kit chat room on Gitter | Visit our sponsors:
The master
branch of React Starter Kit doesn't include a Flux implementation or any other advanced integrations. Nevertheless, we have some integrations available to you in feature branches that you can use either as a reference or merge into your project:
master
)feature/redux
)feature/apollo
)master
)You can see status of most reasonable merge combination as PRs labeled as TRACKING
If you think that any of these features should be on master
, or vice versa, some features should removed from the master
branch, please let us know. We love your feedback!
React Starter Kit
| React Static Boilerplate
| ASP.NET Core Starter Kit
| |
---|---|---|---|
App type | Isomorphic (universal) | Single-page application | Single-page application |
Frontend | |||
Language | JavaScript (ES2015+, JSX) | JavaScript (ES2015+, JSX) | JavaScript (ES2015+, JSX) |
Libraries | React, History, Universal Router | React, History, Redux | React, History, Redux |
Routes | Imperative (functional) | Declarative | Declarative, cross-stack |
Backend | |||
Language | JavaScript (ES2015+, JSX) | n/a | C#, F# |
Libraries | Node.js, Express, Sequelize, GraphQL | n/a | ASP.NET Core, EF Core, ASP.NET Identity |
SSR | Yes | n/a | n/a |
Data API | GraphQL | n/a | Web API |
♥ React Starter Kit? Help us keep it alive by donating funds to cover project expenses via OpenCollective or Bountysource!
Anyone and everyone is welcome to contribute to this project. The best way to start is by checking our open issues, submit a new issue or feature request, participate in discussions, upvote or downvote the issues you like or dislike, send pull requests.
Copyright © 2014-present Kriasoft, LLC. This source code is licensed under the MIT license found in the LICENSE.txt file. The documentation to the project is licensed under the CC BY-SA 4.0 license.
Author: kriasoft
Source Code: https://github.com/kriasoft/react-starter-kit
License: MIT License
1621573085
Expand your user base by using react-native apps developed by our expert team for various platforms like Android, Android TV, iOS, macOS, tvOS, the Web, Windows, and UWP.
We help businesses to scale up the process and achieve greater performance by providing the best react native app development services. Our skilled and experienced team’s apps have delivered all the expected results for our clients across the world.
To achieve growth for your business, hire react native app developers in India. You can count on us for all the technical services and support.
#react native app development company india #react native app developers india #hire react native developers india #react native app development company #react native app developers #hire react native developers
1607768450
In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/
#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks