state
,您还可以为组件类定义方法。类方法通常需要使用this
关键字,以便它可以访问方法范围内的类(例如state
和props
)上的属性。有几种方法可以让您的类方法访问this
。一个常用的方法是显式绑定this
所以在构造this
组件已初始化变为绑定到类方法。您可能已经注意到最后一个挑战使用this.handleClick = this.handleClick.bind(this)
作为构造函数中的handleClick
方法。然后,当您在类方法中调用类似this.setState()
的函数时, this
引用该类,并且不会被undefined
。 注意: this
关键字是JavaScript中最令人困惑的方面之一,但它在React中起着重要作用。虽然这里的行为是完全正常的,但这些课程并不是this
进行深入审查的地方,所以如果上述内容令人困惑,请参考其他课程! state
保持跟踪的项目计数。它还有一个方法,允许您增加此项目计数。但是,该方法不起作用,因为它使用未定义的this
关键字。通过明确地结合修复它this
到addItem()
在组件的构造方法。接下来,将单击处理程序添加到render方法中的button
元素。当按钮收到click事件时,它应该触发addItem()
方法。请记住,传递给onClick
处理程序的方法需要花括号,因为它应该直接解释为JavaScript。完成上述步骤后,您应该可以单击按钮并查看HTML中的项目计数增量。 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
."); };'
```