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

Modifying handleChange to work with multiple fields

The Git tag for this section is handle-change.

After adding all three fields, you will have ended up with three very similar onChange event handlers:

const handleChangeFirstName = ({ target }) =>
setCustomer(customer => ({
...customer,
firstName: target.value
}));

const handleChangeLastName = ({ target }) =>
setCustomer(customer => ({
...customer,
lastName: target.value
}));

const handleChangePhoneNumber = ({ target }) =>
setCustomer(customer => ({
...customer,
phoneNumber: target.value
}));

You can simplify these down into one function, but you'll need to modify your tests first. The calls to ReactTestUtils.Simulate.change needs some extra data to be passed: the target's name. At runtime, this property is passed to all event handlers by React.

Add that in now, as shown:

const itSubmitsNewValue = (fieldName) =>
it('saves new value when submitted', async () => {
...
await ReactTestUtils.Simulate.change(field(fieldName), {
target: { value: 'newValue', name: fieldName }
});
...
});
Test data should always be as simple as possible, by only including what's relevant for the test to pass. We omitted the name property initially because we didn't need it to make our tests pass. Now, we have an opportunity to simplify our production code, so we can include it.

Since the name of our fields is the same as the name of our customer properties, we can now destructure the event to pull out the target name, merging our event handlers into one, as shown. This uses the computed property name feature of ES6:

const handleChange = ({ target }) =>
setCustomer(customer => ({
...customer,
[target.name]: target.value
}));
主站蜘蛛池模板: 定襄县| 柯坪县| 东海县| 永和县| 临桂县| 灵石县| 宿松县| 琼中| 南陵县| 兴仁县| 博客| 车致| 玉龙| 远安县| 万安县| 沂源县| 枞阳县| 建平县| 商城县| 宜黄县| 皮山县| 盐亭县| 红原县| 百色市| 十堰市| 搜索| 隆回县| 巴彦县| 延津县| 北宁市| 乐都县| 昌图县| 宜宾县| 峨边| 靖安县| 那曲县| 乐平市| 阳高县| 廉江市| 英吉沙县| 商丘市|