A React (más néven React.js) az egyik legnépszerűbb JavaScript front end fejlesztői könyvtár. Itt található a React szintaxisának és használatának gyűjteménye, amelyet hasznos útmutatóként vagy referenciaként használhat.
Reakció komponens példa
Az alkatrészek újrafelhasználhatók a React.js fájlban. Az alábbiak szerint adhat értéket a kellékekbe:
function Welcome(props) { return Hello, {props.name}
; } const element = ; ReactDOM.render( element, document.getElementById('root') );
name="Faisal Arkan"
ad értéket {props.name}
származó function Welcome(props)
és a visszatérő olyan összetevő, amely adott értéket name="Faisal Arkan"
. Ezt követően a React html-be teszi az elemet.
Az összetevők deklarálásának egyéb módjai
A React.js használatakor számos módon deklarálhatjuk az összetevőket. Kétféle komponens létezik, a hontalanok és az állapotok .
Államszerű
Osztálytípusú alkatrészek
class Cat extends React.Component { constructor(props) { super(props); this.state = { humor: 'happy' } } render() { return( {this.props.name}
{this.props.color}
); } }
Hontalan alkatrészek
Funkcionális alkatrészek (nyílfüggvény az ES6-tól)
const Cat = props => { return ( {props.name}
{props.color}
; ); };
Implicit Return Components
const Cat = props =>{props.name}
{props.color}
;
Reagáljon töredékre
A töredékek több elem renderelésére szolgálnak burkolóelem használata nélkül. Amikor megkísérli az elemek renderelését bezáró címke nélkül a JSX-ben, megjelenik a hibaüzenet Adjacent JSX elements must be wrapped in an enclosing tag
. Ez azért van, mert amikor a JSX áttelepít, elemeket hoz létre a hozzájuk tartozó címke nevekkel, és nem tudja, milyen címke nevet használjon, ha több elem található.
Korábban ennek gyakori megoldása volt egy burkoló div használatával a probléma megoldására. A React 16. verziója azonban megadta a kiegészítést Fragment
, ami már nem teszi szükségessé.
Fragment
csomagolást végez anélkül, hogy felesleges div-eket adna a DOM-hoz. Használhatja közvetlenül a React importból, vagy dekonstruálhatja:
import React from 'react'; class MyComponent extends React.Component { render(){ return ( I am an element! I am another element ); } } export default MyComponent;
// Deconstructed import React, { Component, Fragment } from 'react'; class MyComponent extends Component { render(){ return ( I am an element! I am another element ); } } export default MyComponent;
A React 16.2 verzió tovább egyszerűsítette ezt a folyamatot, lehetővé téve az üres JSX-címkék töredékekként való értelmezését:
return ( I am an element! I am another element );
Reagáljon a JSX példára
JSX
A JSX a JavaScript XML rövidítése.
A JSX egy olyan kifejezés, amely érvényes HTML utasításokat használ a JavaScript-en belül. Rendelheti ezt a kifejezést egy változóhoz, és máshol is használhatja. Kombinálhat más érvényes JavaScript-kifejezéseket és JSX-eket ezekben a HTML-utasításokban, zárójelek közé helyezve őket ( {}
). Babel tovább fordítja a JSX-t egy típusú objektummá React.createElement()
.
Egysoros és többsoros kifejezések
Az egysoros kifejezés használata egyszerű.
const one = Hello World!
;
Ha több sort kell használnia egyetlen JSX kifejezésben, írja be a kódot egyetlen zárójelbe.
const two = (
- Once
- Twice
);
Csak HTML címkéket használ
const greet = Hello World!
;
A JavaScript kifejezés és a HTML címkék kombinálása
A zárójeleken belül használhatunk JavaScript-változókat.
const who = "Quincy Larson"; const greet = Hello {who}!
;
A zárójeleken belül más JavaScript funkciókat is hívhatunk.
function who() { return "World"; } const greet = Hello {who()}!
;
Csak egy szülő címke engedélyezett
A JSX expression must have only one parent tag. We can add multiple tags nested within the parent element only.
// This is valid. const tags = (
- Once
- Twice
); // This is not valid. const tags = ( Hello World!
This is my special list:
- Once
- Twice
);
React State Example
State is the place where the data comes from.
We should always try to make our state as simple as possible and minimize the number of stateful components. If we have, for example, ten components that need data from the state, we should create one container component that will keep the state for all of them.
State is basically like a global object that is available everywhere in a component.
Example of a Stateful Class Component:
import React from 'react'; class App extends React.Component { constructor(props) { super(props); // We declare the state as shown below this.state = { x: "This is x from state", y: "This is y from state" } } render() { return ( {this.state.x}
{this.state.y}
); } } export default App;
Another Example:
import React from 'react'; class App extends React.Component { constructor(props) { super(props); // We declare the state as shown below this.state = { x: "This is x from state", y: "This is y from state" } } render() { let x1 = this.state.x; let y1 = this.state.y; return ( {x1}
{y1}
); } } export default App;
Updating State
You can change the data stored in the state of your application using the setState
method on your component.
this.setState({ value: 1 });
Keep in mind that setState
is asynchronous so you should be careful when using the current state to set a new state. A good example of this would be if you want to increment a value in your state.
The Wrong Way
this.setState({ value: this.state.value + 1 });
This can lead to unexpected behavior in your app if the code above is called multiple times in the same update cycle. To avoid this you can pass an updater callback function to setState
instead of an object.
The Right Way
this.setState(prevState => ({ value: prevState.value + 1 }));
Updating State
You can change the data stored in the state of your application using the setState
method on your component.
this.setState({value: 1});
Keep in mind that setState
may be asynchronous so you should be careful when using the current state to set a new state. A good example of this would be if you want to increment a value in your state.
The Wrong Way
this.setState({value: this.state.value + 1});
This can lead to unexpected behavior in your app if the code above is called multiple times in the same update cycle. To avoid this you can pass an updater callback function to setState
instead of an object.
The Right Way
this.setState(prevState => ({value: prevState.value + 1}));
The Cleaner Way
this.setState(({ value }) => ({ value: value + 1 }));
When only a limited number of fields in the state object is required, object destructing can be used for cleaner code.
React State VS Props Example
When we start working with React components, we frequently hear two terms. They are state
and props
. So, in this article we will explore what are those and how they differ.
State:
- State is something that a component owns. It belongs to that particular component where it is defined. For example, a person’s age is a state of that person.
- State is mutable. But it can be changed only by that component that owns it. As I only can change my age, not anyone else.
- You can change a state by using
this.setState()
See the below example to get an idea of state:
Person.js
import React from 'react'; class Person extends React.Component{ constructor(props) { super(props); this.state = { age:0 this.incrementAge = this.incrementAge.bind(this) } incrementAge(){ this.setState({ age:this.state.age + 1; }); } render(){ return( My age is: {this.state.age} Grow me older !! ); } } export default Person;
In the above example, age
is the state of Person
component.
Props:
- Props are similar to method arguments. They are passed to a component where that component is used.
- Props is immutable. They are read-only.
See the below example to get an idea of Props:
Person.js
import React from 'react'; class Person extends React.Component{ render(){ return( I am a {this.props.character} person. ); } } export default Person; const person =
In the above example, const person =
we are passing character = "good"
prop to Person
component.
It gives output as “I am a good person”, in fact I am.
There is lot more to learn on State and Props. Many things can be learnt by actually diving into coding. So get your hands dirty by coding.
React Higher-Order Component Example
In React, a Higher-Order Component (HOC) is a function that takes a component and returns a new component. Programmers use HOCs to achieve component logic reuse.
If you’ve used Redux’s connect
, you’ve already worked with Higher-Order Components.
The core idea is:
const EnhancedComponent = enhance(WrappedComponent);
Where:
enhance
is the Higher-Order Component;WrappedComponent
is the component you want to enhance; andEnhancedComponent
is the new component created.
This could be the body of the enhance
HOC:
function enhance(WrappedComponent) { return class extends React.Component { render() { const extraProp = 'This is an injected prop!'; return ( ); } } }
In this case, enhance
returns an anonymous class that extends React.Component
. This new component is doing three simple things:
- Rendering the
WrappedComponent
within adiv
element; - Passing its own props to the
WrappedComponent
; and - Injecting an extra prop to the
WrappedComponent
.
HOCs are just a pattern that uses the power of React’s compositional nature. They add features to a component. There are a lot more things you can do with them!