--- id: 5a24c314108439a4d4036179 title: Create a Controlled Form challengeType: 6 isRequired: false videoUrl: '' localeTitle: Crear un formulario controlado --- ## Description
El último desafío demostró que React puede controlar el estado interno de ciertos elementos como input y textarea , lo que los convierte en componentes controlados. Esto se aplica también a otros elementos de formulario, incluido el elemento de form HTML regular.
## Instructions
El componente MyForm se configura con un form vacío con un controlador de envío. Se llamará al controlador de envío cuando se envíe el formulario. Hemos añadido un botón que envía el formulario. Puede ver que tiene el type conjunto para submit indica que es el botón que controla el formulario. Agregue el elemento de input en el form y establezca su value y los onChange() como el último desafío. Luego debe completar el método handleSubmit para que establezca la propiedad de estado del componente submit al valor de entrada actual en el state local. Nota: También debe llamar a event.preventDefault() en el controlador de envío, para evitar el comportamiento de envío de formulario predeterminado que actualizará la página web. Finalmente, cree una etiqueta h1 después del form que representa el valor de submit del state del componente. Luego puede escribir en el formulario y hacer clic en el botón (o presionar intro), y debería ver su entrada renderizada en la página.
## Tests
```yml tests: - text: MyForm debería devolver un elemento div que contenga un form y una etiqueta h1 . El formulario debe incluir una input y un button . testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyForm)); return (mockedComponent.find("div").children().find("form").length === 1 && mockedComponent.find("div").children().find("h1").length === 1 && mockedComponent.find("form").children().find("input").length === 1 && mockedComponent.find("form").children().find("button").length === 1) })(), "MyForm should return a div element which contains a form and an h1 tag. The form should include an input and a button.");' - text: 'El estado de MyForm debe inicializarse con las propiedades de input y submit , ambas configuradas como cadenas vacías.' testString: 'assert(Enzyme.mount(React.createElement(MyForm)).state("input") === "" && Enzyme.mount(React.createElement(MyForm)).state("submit") === "", "The state of MyForm should initialize with input and submit properties, both set to empty strings.");' - text: Escribir el elemento de input debe actualizar la propiedad de input del estado del componente. testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: "" }); return waitForIt(() => mockedComponent.state("input"))}; const _2 = () => { mockedComponent.find("input").simulate("change", { target: { value: "TestInput" }}); return waitForIt(() => ({ state: mockedComponent.state("input"), inputVal: mockedComponent.find("input").props().value }))}; const before = await _1(); const after = await _2(); assert(before === "" && after.state === "TestInput" && after.inputVal === "TestInput", "Typing in the input element should update the input property of the component's state."); }; ' - text: El envío del formulario debe ejecutar handleSubmit que debe establecer la propiedad de submit en un estado igual a la entrada actual. testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: "" }); mockedComponent.setState({submit: ""}); mockedComponent.find("input").simulate("change", {target: {value: "SubmitInput"}}); return waitForIt(() => mockedComponent.state("submit"))}; const _2 = () => { mockedComponent.find("form").simulate("submit"); return waitForIt(() => mockedComponent.state("submit"))}; const before = await _1(); const after = await _2(); assert(before === "" && after === "SubmitInput", "Submitting the form should run handleSubmit which should set the submit property in state equal to the current input."); };' - text: El encabezado h1 debe representar el valor del campo de submit desde el estado del componente. testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: "" }); mockedComponent.setState({submit: ""}); mockedComponent.find("input").simulate("change", {target: {value: "TestInput"}}); return waitForIt(() => mockedComponent.find("h1").text())}; const _2 = () => { mockedComponent.find("form").simulate("submit"); return waitForIt(() => mockedComponent.find("h1").text())}; const before = await _1(); const after = await _2(); assert(before === "" && after === "TestInput", "The h1 header should render the value of the submit field from the component's state."); }; ' ```
## Challenge Seed
```jsx class MyForm extends React.Component { constructor(props) { super(props); this.state = { input: ", submit: " }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({ input: event.target.value }); } handleSubmit(event) { // change code below this line // change code above this line } render() { return (
{ /* change code below this line */ } { /* change code above this line */ }
{ /* change code below this line */ } { /* change code above this line */ }
); } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```