Files
freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/create-a-stateful-component.chinese.md
Oliver Eyton-Williams 61460c8601 fix: insert blank line after ```
search and replace ```\n< with ```\n\n< to ensure there's an empty line
before closing tags
2020-08-16 04:45:20 +05:30

3.3 KiB
Raw Blame History

id, title, challengeType, isRequired, videoUrl, localeTitle
id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d4036170 Create a Stateful Component 6 false 创建一个有状态组件

Description

React最重要的主题之一是state 。 State包含应用程序需要了解的任何数据这些数据可能会随时间而变化。您希望应用程序响应状态更改并在必要时显示更新的UI。 React为现代Web应用程序的状态管理提供了一个很好的解决方案。您可以通过在constructor声明组件类的state属性来在React组件中创建状态。这与初始化该组件state被创建时。 state属性必须设置为JavaScript object 。声明它看起来像这样:
this.state = {
//在这里描述你的州
您可以在组件的整个生命周期内访问state对象。您可以更新它在UI中呈现它并将其作为道具传递给子组件。 state对象可以像您需要的那样复杂或简单。请注意,您必须通过扩展React.Component来创建类组件,以便创建这样的state

Instructions

代码编辑器中有一个组件试图从其state呈现name属性。但是,没有定义state 。初始化与组件stateconstructor ,并指定你的名字的属性name

Tests

tests:
  - text: <code>StatefulComponent</code>应该存在并呈现。
    testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find('StatefulComponent').length === 1; })());
  - text: <code>StatefulComponent</code>应该呈现<code>div</code>和<code>h1</code>元素。
    testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find('div').length === 1 && mockedComponent.find('h1').length === 1; })());
  - text: 应使用设置为字符串的属性<code>name</code>初始化<code>StatefulComponent</code> 。
    testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return ( typeof initialState === 'object' && typeof initialState.name === 'string'); })());
  - text: <code>StatefulComponent</code>的属性<code>name</code>应在<code>h1</code>元素中呈现。
    testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return mockedComponent.find('h1').text() === initialState.name; })());

Challenge Seed

class StatefulComponent extends React.Component {
  constructor(props) {
    super(props);
    // initialize state here

  }
  render() {
    return (
      <div>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};

After Test

console.info('after the test');

Solution

// solution required

/section>