--- id: 5a24c314108439a4d4036172 title: Render State in the User Interface Another Way challengeType: 6 isRequired: false videoUrl: '' localeTitle: 用户界面中的渲染状态另一种方式 --- ## Description
还有另一种访问组件中state方法。在render()方法中,在return语句之前,您可以直接编写JavaScript。例如,您可以声明函数,从stateprops访问数据,对此数据执行计算,等等。然后,您可以将任何数据分配给您可以在return语句中访问的变量。
## Instructions
MyComponent render方法中,定义一个名为nameconst ,并将其设置为等于组件state的name值。因为您可以直接在代码的这一部分编写JavaScript,所以您不必将此引用括在花括号中。接下来,在return语句中,使用变量nameh1标记中呈现此值。请记住,您需要在return语句中使用JSX语法(JavaScript的大括号)。
## Tests
```yml tests: - text: MyComponent应该有一个键name ,其freeCodeCamp值存储在其状态中。 testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("name") === "freeCodeCamp", "MyComponent should have a key name with value freeCodeCamp stored in its state.");' - text: MyComponent应该渲染一个包含在单个divh1标头。 testString: 'assert(/

.*<\/h1><\/div>/.test(Enzyme.mount(React.createElement(MyComponent)).html()), "MyComponent should render an h1 header enclosed in a single div.");' - text: '渲染的h1标记应包含对{name}的引用。' testString: 'getUserInput => assert(/

\n*\s*\{\s*name\s*\}\s*\n*<\/h1>/.test(getUserInput("index")), "The rendered h1 tag should include a reference to {name}.");' - text: 渲染的h1标头应包含从组件状态呈现的文本。 testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: "TestName" }); return waitForIt(() => mockedComponent.html()) }; const firstValue = await first(); assert(firstValue === "

TestName

", "The rendered h1 header should contain text rendered from the component's state."); };' ```

## Challenge Seed
```jsx class MyComponent extends React.Component { constructor(props) { super(props); this.state = { name: 'freeCodeCamp' } } render() { // change code below this line // change code above this line return (
{ /* change code below this line */ } { /* change code above this line */ }
); } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```