مكونات صنف رد الفعل
قبل React 16.8 ، كانت مكونات الصنف هي الطريقة الوحيدة لتتبع الحالة ودورة الحياة لمكوِّن React. تم اعتبار مكونات الوظيفة "أقل حالة".
مع إضافة الخطافات ، أصبحت مكونات الوظيفة الآن مكافئة تقريبًا لمكونات الفئة. الاختلافات طفيفة جدًا لدرجة أنك لن تحتاج أبدًا إلى استخدام مكون Class في React.
على الرغم من تفضيل مكونات الوظيفة ، لا توجد خطط حالية لإزالة مكونات الفئة من React.
سيعطيك هذا القسم نظرة عامة حول كيفية استخدام مكونات الصنف في React.
لا تتردد في تخطي هذا القسم ، واستخدام مكونات الوظيفة بدلاً من ذلك.
مكونات رد الفعل
المكونات مستقلة وقابلة لإعادة الاستخدام بتات من التعليمات البرمجية. إنها تخدم نفس الغرض مثل وظائف JavaScript ، ولكنها تعمل بمعزل عن ملفات HTML وتعيدها عبر وظيفة تقديم ().
تأتي المكونات في نوعين ، مكونات الفئة ومكونات الوظيفة ، في هذا الفصل ستتعرف على مكونات الفئة.
قم بإنشاء مكون فئة
عند إنشاء مكون React ، يجب أن يبدأ اسم المكون بحرف كبير.
يجب أن يشتمل المكون على extends React.Component
العبارة ، هذه العبارة تخلق وراثة لـ React.Component ، وتمنح المكون الخاص بك إمكانية الوصول إلى وظائف React.Component.
يتطلب المكون أيضًا render()
طريقة ، وتعيد هذه الطريقة HTML.
مثال
قم بإنشاء مكون فئة يسمىCar
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
الآن يحتوي تطبيق React الخاص بك على مكون يسمى Car ، والذي يقوم بإرجاع
<h2>
عنصر.
لاستخدام هذا المكون في تطبيقك ، استخدم بنية مشابهة مثل HTML العادي:
<Car />
مثال
اعرض Car
المكون في عنصر "الجذر":
ReactDOM.render(<Car />, document.getElementById('root'));
الحصول على شهادة!
95 دولارًا ENROLL
منشئ المكونات
إذا كانت هناك
وظيفة في المكون الخاص بك ، فسيتم استدعاء هذه الوظيفة عند بدء المكون.constructor()
وظيفة المُنشئ هي المكان الذي تبدأ فيه خصائص المكون.
في React ، يجب الاحتفاظ بخصائص المكون في كائن يسمى
state
.
سوف تتعلم المزيد عنها state
لاحقًا في هذا البرنامج التعليمي.
وظيفة المُنشئ هي أيضًا المكان الذي تحترم فيه وراثة المكون الرئيسي من خلال تضمين super()
العبارة ، التي تنفذ وظيفة مُنشئ المكون الأصلي ، ويكون للمكون الخاص بك حق الوصول إلى جميع وظائف المكون الرئيسي ( React.Component
).
مثال
أنشئ دالة مُنشئ في مكون السيارة ، وأضف خاصية اللون:
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a Car!</h2>;
}
}
استخدم خاصية color في دالة العرض ():
مثال
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a {this.state.color} Car!</h2>;
}
}
الدعائم
هناك طريقة أخرى للتعامل مع خصائص المكون وهي باستخدام props
.
تعتبر الدعائم مثل وسيطات الوظيفة ، ويمكنك إرسالها إلى المكون كسمات.
سوف تتعلم المزيد عنها props
في الفصل التالي.
مثال
استخدم سمة لتمرير لون إلى مكون السيارة ، واستخدمها في وظيفة العرض ():
class Car extends React.Component {
render() {
return <h2>I am a {this.props.color} Car!</h2>;
}
}
ReactDOM.render(<Car color="red"/>, document.getElementById('root'));
الدعائم في المنشئ
إذا كان للمكوِّن الخاص بك دالة مُنشئ ، فيجب دائمًا تمرير الخاصيات إلى المُنشئ وأيضًا إلى React.Component عبر التابع super()
.
مثال
class Car extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h2>I am a {this.props.model}!</h2>;
}
}
ReactDOM.render(<Car model="Mustang"/>, document.getElementById('root'));
المكونات في المكونات
يمكننا الإشارة إلى المكونات الموجودة داخل المكونات الأخرى:
مثال
استخدم مكون السيارة داخل مكون Garage:
class Car extends React.Component {
render() {
return <h2>I am a Car!</h2>;
}
}
class Garage extends React.Component {
render() {
return (
<div>
<h1>Who lives in my Garage?</h1>
<Car />
</div>
);
}
}
ReactDOM.render(<Garage />, document.getElementById('root'));
المكونات في الملفات
يتمحور React حول إعادة استخدام التعليمات البرمجية ، ويمكن أن يكون من الذكاء إدراج بعض مكوناتك في ملفات منفصلة.
للقيام بذلك ، قم بإنشاء ملف جديد .js
بامتداد ملف ووضع الكود بداخله:
لاحظ أن الملف يجب أن يبدأ باستيراد React (كما كان من قبل) ، ويجب أن ينتهي بالعبارة export default Car;
.
مثال
هذا هو الملف الجديد ، قمنا بتسميته Car.js
:
import React from 'react';
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
export default Car;
لتتمكن من استخدام Car
المكون ، يجب عليك استيراد الملف في التطبيق الخاص بك.
مثال
الآن نقوم باستيراد Car.js
الملف في التطبيق ، ويمكننا استخدام
Car
المكون كما لو تم إنشاؤه هنا.
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './Car.js';
ReactDOM.render(<Car />, document.getElementById('root'));
رد فعل حالة مكون فئة
تحتوي مكونات فئة React على state
كائن مدمج.
ربما لاحظت أننا استخدمنا state
سابقًا في قسم مُنشئ المكون.
الكائن state
هو المكان الذي تخزن فيه قيم الخصائص التي تنتمي إلى المكون.
عندما state
يتغير الكائن ، يعيد المكون تصيير.
إنشاء كائن الدولة
تتم تهيئة كائن الحالة في المُنشئ:
مثال
حدد state
الكائن في طريقة الباني:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
يمكن أن يحتوي كائن الحالة على العديد من الخصائص كما تريد:
مثال
حدد جميع الخصائص التي يحتاجها المكون الخاص بك:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
باستخدام state
الكائن
ارجع إلى state
الكائن في أي مكان في المكون باستخدام
بناء الجملة:this.state.propertyname
مثال:
الرجوع إلى state
الكائن في
render()
الطريقة:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
</div>
);
}
}
تغيير state
الكائن
لتغيير قيمة في كائن الحالة ، استخدم this.setState()
الطريقة.
عندما تتغير قيمة في state
الكائن ، سيعاد تقديم المكون ، مما يعني أن الناتج سيتغير وفقًا للقيمة (القيم) الجديدة.
مثال:
أضف زرًا onClick
بحدث سيغير خاصية اللون:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
<button
type="button"
onClick={this.changeColor}
>Change color</button>
</div>
);
}
}
استخدم setState()
الطريقة دائمًا لتغيير كائن الحالة ، وسيضمن أن يعرف المكون أنه تم تحديثه ويستدعي طريقة العرض () (وجميع توابع دورة الحياة الأخرى).
دورة حياة المكونات
لكل مكون في React دورة حياة يمكنك مراقبتها ومعالجتها خلال مراحلها الرئيسية الثلاث.
المراحل الثلاث هي : التثبيت والتحديث والفك .
تصاعد
التركيب يعني وضع العناصر في DOM.
تحتوي React على أربع توابع مضمنة يتم استدعاؤها ، بهذا الترتيب ، عند تركيب مكوِّن:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
الطريقة مطلوبة وسيتم الاتصال بها دائمًا ، أما render()
الطرق الأخرى فهي اختيارية وسيتم استدعاؤها إذا حددتها.
constructor
يتم constructor()
استدعاء الطريقة قبل أي شيء آخر ، عند بدء المكون ، وهي المكان الطبيعي لإعداد state
القيم الأولية والقيم الأولية الأخرى.
يُستدعى هذا constructor()
الأسلوب باستخدام
props
الوسيطات ، ويجب أن تبدأ دائمًا باستدعاء super(props)
قبل أي شيء آخر ، وهذا سيبدأ طريقة مُنشئ الأصل ويسمح للمكون أن يرث العمليات من أصله ( React.Component
).
مثال:
يتم constructor
استدعاء العملية ، بواسطة React ، في كل مرة تقوم فيها بإنشاء مكون:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
getDerivedStateFromProps
يتم getDerivedStateFromProps()
استدعاء الطريقة مباشرة قبل عرض العنصر (العناصر) في DOM.
هذا هو المكان الطبيعي لتعيين state
الكائن بناءً على الحرف الأول
props
.
It takes
state
as an argument, and returns an object with changes to the
state
.
The example below starts with the favorite color being
"red", but the
getDerivedStateFromProps()
method updates the favorite color based on the
favcol
attribute:
Example:
The getDerivedStateFromProps
method is called
right before the render method:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));
render
The render()
method is required, and is the
method that actually outputs the HTML to the DOM.
Example:
A simple component with a simple render()
method:
class Header extends React.Component {
render() {
return (
<h1>This is the content of the Header component</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
componentDidMount
The componentDidMount()
method is called after the
component is rendered.
This is where you run statements that requires that the component is already placed in the DOM.
Example:
At first my favorite color is red, but give me a second, and it is yellow instead:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Updating
The next phase in the lifecycle is when a component is updated.
A component is updated whenever there is a change in the component's
state
or props
.
React has five built-in methods that gets called, in this order, when a component is updated:
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
The render()
method is required and will
always be called, the others are optional and will be called if you define them.
getDerivedStateFromProps
Also at updates the getDerivedStateFromProps
method is
called. This is the first method that is called when a component gets updated.
This is still the natural place to set the state
object based on the initial props.
The example below has a button that changes the favorite color to blue, but
since the getDerivedStateFromProps()
method is called,
which updates the state with the color from the favcol attribute, the favorite color is
still
rendered as yellow:
Example:
If the component gets updated, the getDerivedStateFromProps()
method is called:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));
shouldComponentUpdate
In the shouldComponentUpdate()
method
you can return a Boolean value that specifies whether React should continue with the rendering or not.
The default value is true
.
The example below shows what happens when the
shouldComponentUpdate()
method returns false
:
Example:
Stop the component from rendering at any update:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Example:
Same example as above, but this time the shouldComponentUpdate()
method returns
true
instead:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return true;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
render
The render()
method is of course called when a component gets updated,
it has to re-render the HTML to the DOM, with the new changes.
The example below has a button that changes the favorite color to blue:
Example:
Click the button to make a change in the component's state:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
getSnapshotBeforeUpdate
In the getSnapshotBeforeUpdate()
method
you have access to the props
and
state
before the update, meaning that
even after the update, you can check what the values were before the
update.
If the getSnapshotBeforeUpdate()
method
is present, you should also include the
componentDidUpdate()
method, otherwise you will get an error.
The example below might seem complicated, but all it does is this:
When the component is mounting it is rendered with the favorite color "red".
When the component has been mounted, a timer changes the state, and after one second, the favorite color becomes "yellow".
This action triggers the update phase, and since this component has a
getSnapshotBeforeUpdate()
method, this method is executed, and writes a
message to the empty DIV1 element.
Then the componentDidUpdate()
method is
executed and writes a message in the empty DIV2 element:
Example:
Use the
getSnapshotBeforeUpdate()
method to find out
what the state
object looked like before
the update:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
"Before the update, the favorite was " + prevState.favoritecolor;
}
componentDidUpdate() {
document.getElementById("div2").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
componentDidUpdate
The componentDidUpdate
method
is called after the component is updated in the DOM.
The example below might seem complicated, but all it does is this:
When the component is mounting it is rendered with the favorite color "red".
When the component has been mounted, a timer changes the state, and the color becomes "yellow".
This action triggers the update phase, and since this component has
a componentDidUpdate
method, this method is
executed and writes a message in the empty DIV element:
Example:
The componentDidUpdate
method is called
after the update has been rendered in the DOM:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
componentDidUpdate() {
document.getElementById("mydiv").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="mydiv"></div>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Unmounting
The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it.
React has only one built-in method that gets called when a component is unmounted:
componentWillUnmount()
componentWillUnmount
The componentWillUnmount
method is
called when the component is about to be removed from the DOM.
Example:
Click the button to delete the header:
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
render() {
let myheader;
if (this.state.show) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={this.delHeader}>Delete Header</button>
</div>
);
}
}
class Child extends React.Component {
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}
ReactDOM.render(<Container />, document.getElementById('root'));