--- id: 5a24c314108439a4d4036176 title: Use State to Toggle an Element challengeType: 6 isRequired: false videoUrl: '' localeTitle: 使用State切换元素 --- ## Description
您可以以比您目前所见的更复杂的方式在React应用程序中使用state 。一个示例是监视值的状态,然后根据此值有条件地呈现UI。有几种不同的方法可以实现这一点,代码编辑器显示了一种方法。
## Instructions
MyComponent有一个visibility属性,初始化为false 。如果visibility值为true,则render方法返回一个视图;如果为false,则返回不同的视图。目前,无法更新组件statevisibility属性。该值应在true和false之间来回切换。按钮上有一个单击处理程序,它触发一个名为toggleVisibility()的类方法。定义此方法,以便在调用方法时, visibility state切换为相反的值。如果visibilityfalse ,该方法将其设置为true ,反之亦然。最后,单击按钮以根据其state查看组件的条件呈现。 提示:不要忘记将this关键字绑定到构造函数中的方法!
## Tests
```yml tests: - text: MyComponent应该返回一个包含buttondiv元素。 testString: 'assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).find("div").find("button").length, 1, "MyComponent should return a div element which contains a button.");' - text: MyComponent的状态应该初始化,并将visibility属性设置为false 。 testString: 'assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).state("visibility"), false, "The state of MyComponent should initialize with a visibility property set to false.");' - text: 单击按钮元素应该在truefalse之间切换状态的visibility属性。 testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ visibility: false }); return waitForIt(() => mockedComponent.state("visibility")); }; const second = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent.state("visibility")); }; const third = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent.state("visibility")); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(!firstValue && secondValue && !thirdValue, "Clicking the button element should toggle the visibility property in state between true and false."); }; ' ```
## Challenge Seed
```jsx class MyComponent extends React.Component { constructor(props) { super(props); this.state = { visibility: false }; // change code below this line // change code above this line } // change code below this line // change code above this line render() { if (this.state.visibility) { return (

Now you see me!

); } else { return (
); } } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```