3.7 KiB
3.7 KiB
id | title | challengeType | isRequired | videoUrl | localeTitle |
---|---|---|---|---|---|
5a24c314108439a4d4036170 | Create a Stateful Component | 6 | false | 创建一个有状态组件 |
Description
state
。 State包含应用程序需要了解的任何数据,这些数据可能会随时间而变化。您希望应用程序响应状态更改并在必要时显示更新的UI。 React为现代Web应用程序的状态管理提供了一个很好的解决方案。您可以通过在constructor
声明组件类的state
属性来在React组件中创建状态。这与初始化该组件state
被创建时。 state
属性必须设置为JavaScript object
。声明它看起来像这样: this.state = {
//在这里描述你的州
您可以在组件的整个生命周期内访问state
对象。您可以更新它,在UI中呈现它,并将其作为道具传递给子组件。state
对象可以像您需要的那样复杂或简单。请注意,您必须通过扩展React.Component
来创建类组件,以便创建这样的state
。
Instructions
state
呈现name
属性。但是,没有定义state
。初始化与组件state
的constructor
,并指定你的名字的属性name
。 Tests
tests:
- text: <code>StatefulComponent</code>应该存在并呈现。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find("StatefulComponent").length === 1; })(), "<code>StatefulComponent</code> should exist and render.");'
- 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; })(), "<code>StatefulComponent</code> should render a <code>div</code> and an <code>h1</code> element.");'
- 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"); })(), "The state of <code>StatefulComponent</code> should be initialized with a property <code>name</code> set to a 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; })(), "The property <code>name</code> in the state of <code>StatefulComponent</code> should render in the <code>h1</code> element.");'
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