官术网_书友最值得收藏!

Using state instead of props

It's finally time to introduce some state into our component. Add the following test, which what should happen when the text field value changes:

it('saves new first name when submitted', async () => {
expect.hasAssertions();
render(
<CustomerForm
firstName="Ashley"
onSubmit={({ firstName }) =>
expect(firstName).toEqual('Jamie')
}
/>
);
await ReactTestUtils.Simulate.change( firstNameField(), {
target: { value: 'Jamie' }
});
await ReactTestUtils.Simulate.submit(form('customer'));
});

The call to Simulate.change dispatches a React onChange event to the field. The event object sends the value of the text field to the event handler, which we'll use to set state.

In the browser, this event would be dispatched after every keystroke; however, in our test, we simulate just the final change event. That's enough because we'll write our event handler to always overwrite previous changes. In other words, only the last change matters.

Follow these steps to make this pass:

  1. Import useState into the module by modifying the existing React import:
import React, { useState } from 'react';
  1. Change the customer constant definition to be assigned via a call to useState. The default state is the original value of customer. Note the relationship between the two pieces of code. This is an example of how we can "upgrade" existing code from one level of complexity to another—in this case, from a constant definition to a state variable:
const [ customer, setCustomer ] = useState({ firstName });
  1. Create a new arrow function that will act as our event handler. This uses the form of setCustomer that takes a function. Using this form ensures that we correctly apply updates in the right order:
const handleChangeFirstName = ({ target }) =>
setCustomer(customer => ({
...customer,
firstName: target.value
}));
  1. In the returned JSX, modify the input element as shown. We replace the readOnly property with an onChange property, hooking it up to the handler we just created:
<input
type="text"
name="firstName"
id="firstName"
value={firstName}
onChange={handleChangeFirstName}
/>
主站蜘蛛池模板: 青冈县| 民乐县| 莎车县| 郯城县| 东台市| 静宁县| 资源县| 桐庐县| 博客| 甘洛县| 汨罗市| 健康| 晋宁县| 南京市| 广灵县| 北碚区| 遵化市| 浏阳市| 西乌珠穆沁旗| 左云县| 宁津县| 内黄县| 马尔康县| 海林市| 通城县| 息烽县| 右玉县| 木里| 敦化市| 大悟县| 兴安盟| 施秉县| 锦州市| 景德镇市| 扎赉特旗| 阿合奇县| 吉安县| 轮台县| 吴江市| 西乌珠穆沁旗| 保靖县|