state
، يمكنك أيضًا تحديد طرق لفئة مكونك. عادةً ما تحتاج طريقة الصف إلى استخدام this
الكلمة الرئيسية حتى تتمكن من الوصول إلى الخصائص على الفئة (مثل state
props
) داخل نطاق الطريقة. هناك عدة طرق للسماح لطرق صفك بالوصول إلى this
. إحدى الطرق الشائعة هي ربط this
بشكل صريح في المُنشئ بحيث يصبح this
مرتبطًا بطرق الفئة عند تهيئة المكون. ربما تكون قد لاحظت التحدي الأخير الذي استخدمه this.handleClick = this.handleClick.bind(this)
لأسلوب handleClick
الخاص به في المُنشئ. ثم ، عند استدعاء دالة مثل هذا this.setState()
داخل أسلوب الفصل ، يشير this
إلى الفئة ولن يكون undefined
. ملاحظة: تعتبر this
الكلمة الرئيسية واحدة من أكثر جوانب جافا سكريبت مربكة ولكنها تلعب دورًا مهمًا في التفاعل. على الرغم من أن سلوكه هنا طبيعي تمامًا ، إلا أن هذه الدروس ليست المكان المناسب لمراجعة متعمقة this
لذا يرجى الرجوع إلى دروس أخرى إذا كان ما سبق مثيرًا للإرباك! MyComponent
بإرجاع عنصر div
يلف عنصرين ، زر و عنصر h1
، بهذا الترتيب.
testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).find("div").length === 1 && Enzyme.mount(React.createElement(MyComponent)).find("div").childAt(0).type() === "button" && Enzyme.mount(React.createElement(MyComponent)).find("div").childAt(1).type() === "h1", "MyComponent
should return a div
element which wraps two elements, a button and an h1
element, in that order.");'
- text: 'يجب تهيئة حالة MyComponent
مع زوج القيمة الرئيسية { itemCount: 0 }
.'
testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("itemCount") === 0, "The state of MyComponent
should initialize with the key value pair { itemCount: 0 }
.");'
- text: بالنقر على button
يجب أن عنصر تشغيل addItem
طريقة وزيادة الدولة itemCount
من 1
.
testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ itemCount: 0 }); return waitForIt(() => mockedComponent.state("itemCount")); }; const second = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent.state("itemCount")); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === 0 && secondValue === 1, "Clicking the button
element should run the addItem
method and increment the state itemCount
by 1
."); };'
```