3.0 KiB
3.0 KiB
id | title | challengeType | isRequired | videoUrl | localeTitle |
---|---|---|---|---|---|
5a24c314108439a4d4036163 | Create a React Component | 6 | false | 创建一个React组件 |
Description
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!
的h1
的div
元素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