--- id: 5a24c314108439a4d4036174 title: Bind 'this' to a Class Method challengeType: 6 isRequired: false videoUrl: '' localeTitle: 将'this'绑定到类方法 --- ## Description
除了设置和更新state ,您还可以为组件类定义方法。类方法通常需要使用this关键字,以便它可以访问方法范围内的类(例如stateprops )上的属性。有几种方法可以让您的类方法访问this 。一个常用的方法是显式绑定this所以在构造this组件已初始化变为绑定到类方法。您可能已经注意到最后一个挑战使用this.handleClick = this.handleClick.bind(this)作为构造函数中的handleClick方法。然后,当您在类方法中调用类似this.setState()的函数时, this引用该类,并且不会被undefined注意: this关键字是JavaScript中最令人困惑的方面之一,但它在React中起着重要作用。虽然这里的行为是完全正常的,但这些课程并不是this进行深入审查的地方,所以如果上述内容令人困惑,请参考其他课程!
## Instructions
代码编辑器具有与组件state保持跟踪的项目计数。它还有一个方法,允许您增加此项目计数。但是,该方法不起作用,因为它使用未定义的this关键字。通过明确地结合修复它thisaddItem()在组件的构造方法。接下来,将单击处理程序添加到render方法中的button元素。当按钮收到click事件时,它应该触发addItem()方法。请记住,传递给onClick处理程序的方法需要花括号,因为它应该直接解释为JavaScript。完成上述步骤后,您应该可以单击按钮并查看HTML中的项目计数增量。
## Tests
```yml tests: - text: 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."); };' ```
## Challenge Seed
```jsx class MyComponent extends React.Component { constructor(props) { super(props); this.state = { itemCount: 0 }; // change code below this line // change code above this line } addItem() { this.setState({ itemCount: this.state.itemCount + 1 }); } render() { return (
{ /* change code below this line */ } { /* change code above this line */ }

Current Item Count: {this.state.itemCount}

); } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```