state 。一个示例是监视值的状态,然后根据此值有条件地呈现UI。有几种不同的方法可以实现这一点,代码编辑器显示了一种方法。 MyComponent有一个visibility属性,初始化为false 。如果visibility值为true,则render方法返回一个视图;如果为false,则返回不同的视图。目前,无法更新组件state的visibility属性。该值应在true和false之间来回切换。按钮上有一个单击处理程序,它触发一个名为toggleVisibility()的类方法。定义此方法,以便在调用方法时, visibility state切换为相反的值。如果visibility是false ,该方法将其设置为true ,反之亦然。最后,单击按钮以根据其state查看组件的条件呈现。 提示:不要忘记将this关键字绑定到构造函数中的方法! MyComponent应该返回一个包含button的div元素。
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: 单击按钮元素应该在true和false之间切换状态的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."); }; '
```