freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/create-a-react-component.ch...

3.0 KiB
Raw Blame History

id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d4036163 Create a React Component 6 false 创建一个React组件

Description

定义React组件的另一种方法是使用ES6 class语法。在以下示例中, Kitten扩展了React.Component
class Kitten扩展了React.Component {
构造函数(道具){
超级(道具);
}

render{
回来(
<H1>,您好</ H1>
;
}
}
这将创建一个扩展React.Component类的ES6类Kitten 。因此, Kitten类现在可以访问许多有用的React功能例如本地状态和生命周期钩子。如果您还不熟悉这些术语请不要担心在以后的挑战中将更详细地介绍它们。另请注意 Kitten类在其中定义了一个调用super()constructor函数。它使用super()来调用父类的构造函数,在本例中为React.Component 。构造函数是在使用class关键字创建的对象初始化期间使用的特殊方法。最好用super调用组件的constructor ,并将props传递给它们。这可确保组件正确初始化。现在,请知道包含此代码是标准的。很快你会看到构造函数和props其他用途。

Instructions

MyComponent是使用类语法在代码编辑器中定义的。完成编写render方法,以便返回包含带有文本Hello React!h1div元素Hello React!

Tests

tests:
  - text: React组件应返回<code>div</code>元素。
    testString: 'assert(Enzyme.shallow(React.createElement(MyComponent)).type() === "div", "The React component should return a <code>div</code> element.");'
  - text: 返回的<code>div</code>应该在其中呈现一个<code>h1</code>头。
    testString: 'assert(/<div><h1>.*<\/h1><\/div>/.test(Enzyme.shallow(React.createElement(MyComponent)).html()), "The returned <code>div</code> should render an <code>h1</code> header within it.");'
  - text: <code>h1</code>标头应该包含字符串<code>Hello React!</code> 。
    testString: 'assert(Enzyme.shallow(React.createElement(MyComponent)).html() === "<div><h1>Hello React!</h1></div>", "The <code>h1</code> header should contain the string <code>Hello React!</code>.");'

Challenge Seed

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



    // change code above this line
  }
};

After Test

console.info('after the test');

Solution

// solution required