freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/bind-this-to-a-class-method...

4.6 KiB
Raw Blame History

id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d4036174 Bind 'this' to a Class Method 6 false 将'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

tests:
  - text: <code>MyComponent</code>应该返回一个<code>div</code>元素,它按顺序包装两个元素,一个按钮和一个<code>h1</code>元素。
    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", "<code>MyComponent</code> should return a <code>div</code> element which wraps two elements, a button and an <code>h1</code> element, in that order.");'
  - text: '<code>MyComponent</code>的状态应使用键值对<code>{ itemCount: 0 }</code>初始化。'
    testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("itemCount") === 0, "The state of <code>MyComponent</code> should initialize with the key value pair <code>{ itemCount: 0 }</code>.");'
  - text: 单击<code>button</code>元素应该运行<code>addItem</code>方法并将状态<code>itemCount</code>递增<code>1</code> 。
    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 <code>button</code> element should run the <code>addItem</code> method and increment the state <code>itemCount</code> by <code>1</code>."); };'

Challenge Seed

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 (
      <div>
        { /* change code below this line */ }
        <button>Click Me</button>
        { /* change code above this line */ }
        <h1>Current Item Count: {this.state.itemCount}</h1>
      </div>
    );
  }
};

After Test

console.info('after the test');

Solution

// solution required