state
en las aplicaciones React de formas más complejas que las que ha visto hasta ahora. Un ejemplo es monitorear el estado de un valor, luego renderizar la IU condicionalmente en base a este valor. Hay varias maneras diferentes de lograr esto, y el editor de código muestra un método. MyComponent
tiene una propiedad de visibility
que se inicializa en false
. El método de renderización devuelve una vista si el valor de visibility
es verdadero y una vista diferente si es falsa. Actualmente, no hay forma de actualizar la propiedad de visibility
en el state
del componente. El valor debe alternar entre verdadero y falso. Hay un controlador de clic en el botón que activa un método de clase llamado toggleVisibility()
. Defina este método para que el state
de visibility
cambie al valor opuesto cuando se llama al método. Si la visibility
es false
, el método lo establece en true
y viceversa. Finalmente, haga clic en el botón para ver la representación condicional del componente en función de su state
. Sugerencia: ¡No olvide enlazar this
palabra clave con el método en el constructor! MyComponent
debería devolver un elemento div
que contenga un button
.
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: El estado de MyComponent
debe inicializarse con una propiedad de visibility
establecida en 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: Al hacer clic en el elemento del botón se debe cambiar la propiedad de visibility
en estado entre true
y false
.
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
."); }; '
```