Files
freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/create-a-react-component.md
Oliver Eyton-Williams ee1e8abd87 feat(curriculum): restore seed + solution to Chinese (#40683)
* feat(tools): add seed/solution restore script

* chore(curriculum): remove empty sections' markers

* chore(curriculum): add seed + solution to Chinese

* chore: remove old formatter

* fix: update getChallenges

parse translated challenges separately, without reference to the source

* chore(curriculum): add dashedName to English

* chore(curriculum): add dashedName to Chinese

* refactor: remove unused challenge property 'name'

* fix: relax dashedName requirement

* fix: stray tag

Remove stray `pre` tag from challenge file.

Signed-off-by: nhcarrigan <nhcarrigan@gmail.com>

Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2021-01-12 19:31:00 -07:00

2.5 KiB
Raw Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
5a24c314108439a4d4036163 创建一个 React 组件 6 301386 create-a-react-component

--description--

定义 React 组件的另一种方法是使用 ES6 的class语法。在以下示例中,Kitten扩展了React.Component

class Kitten extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <h1>Hi</h1>
    );
  }
}

这将创建一个 ES6 类Kitten,它扩展了React.Component类。因此,Kitten类现在可以访问许多有用的 React 功能,例如本地状态和生命周期钩子。如果你还不熟悉这些术语,请不要担心,在以后的挑战中我们将更详细地介绍它们。 另请注意,Kitten类中定义了一个调用super()方法的constructor。它使用super()调用父类的构造函数,即本例中的React.Component。构造函数是使用class关键字创建的特殊方法,它用在实例初始化之前。最佳做法是在组件的constructor里调用super,并将props传递给它们,这样可以保证组件能够正确地初始化。现在,你只需要知道这是标准的做法。很快你会看到构造函数的其他用途以及props

--instructions--

MyComponent是使用类语法在代码编辑器中定义的。完成render方法的编写,使其返回div元素,其中包含文本内容为Hello React!h1元素。

--hints--

该 React 组件应该返回一个div元素。

assert(Enzyme.shallow(React.createElement(MyComponent)).type() === 'div');

返回的div中应该渲染一个h1标题。

assert(
  /<div><h1>.*<\/h1><\/div>/.test(
    Enzyme.shallow(React.createElement(MyComponent)).html()
  )
);

h1标题中应该包含字符串Hello React!

assert(
  Enzyme.shallow(React.createElement(MyComponent)).html() ===
    '<div><h1>Hello React!</h1></div>'
);

--seed--

--after-user-code--

ReactDOM.render(<MyComponent />, document.getElementById('root'))

--seed-contents--

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    // Change code below this line



    // Change code above this line
  }
};

--solutions--

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    // Change code below this line
    return (
      <div>
        <h1>Hello React!</h1>
      </div>
    );
    // Change code above this line
  }
};