else if
语句来返回略有不同的UI,你可能会重复代码,这会留下错误的余地。相反,您可以使用&&
logical运算符以更简洁的方式执行条件逻辑。这是可能的,因为您要检查条件是否为true
,如果是,则返回一些标记。下面是一个示例: {condition && <p>markup</p>}
如果condition
为true
,则返回标记。如果条件为false
,则在评估condition
后操作将立即返回false
并且不返回任何内容。您可以直接在JSX中包含这些语句,并在每个语句之后写入&&
多个条件串在一起。这允许您在render()
方法中处理更复杂的条件逻辑,而无需重复大量代码。 h1
仅在display
为true
呈现,但使用&&
logical运算符而不是if/else
语句。 MyComponent
应该存在并呈现。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find("MyComponent").length; })(), "MyComponent
should exist and render.");'
- text: 当display
设置为true
,应该渲染div
, button
和h1
。
testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: true}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find("div").length === 1 && updated.find("div").children().length === 2 && updated.find("button").length === 1 && updated.find("h1").length === 1, "When display
is set to true
, a div
, button
, and h1
should render."); }; '
- text: 当display
设置为false
,只应呈现div
和button
。
testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: false}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find("div").length === 1 && updated.find("div").children().length === 1 && updated.find("button").length === 1 && updated.find("h1").length === 0, "When display
is set to false
, only a div
and button
should render."); }; '
- text: render方法应该使用&& logical运算符来检查this.state.display的条件。
testString: 'getUserInput => assert(getUserInput("index").includes("&&"), "The render method should use the && logical operator to check the condition of this.state.display.");'
```