我发现似乎是一个很好的解决方案:使用key
props强制渲染一个全新的input
.
在我的特殊情况下,我不需要input
用自己的onChange
props来控制,因为它form
周围的环境最终会控制填充defaultValue
. 但是商店的状态可能会被异步初始化/更新,在这种情况下defaultValue
应该更新。所以这是我的特殊情况的浓缩版本:
import React, { PropTypes } from 'react';
import { Form } from 'provide-page';
const GatherContact = ({
classes,
onSubmit,
movingContactName,
movingContactEmail,
movingContactPhone,
userName,
userEmail,
userPhone
}) => (
<Form onSubmit={onSubmit}>
<div className={classes.GatherContact}>
<h2 className={classes.GatherHeading}>
How can we contact you?
</h2>
<input
type="text"
className={classes.GatherContactInput}
placeholder="Name"
name="movingContactName"
key={`movingContactName:${movingContactName || userName}`}
defaultValue={movingContactName || userName}
required={true}
/>
<input
type="email"
className={classes.GatherContactInput}
placeholder="Email"
name="movingContactEmail"
key={`movingContactEmail:${movingContactEmail || userEmail}`}
defaultValue={movingContactEmail || userEmail}
required={true}
/>
<input
type="tel"
className={classes.GatherContactInput}
placeholder="Phone"
name="movingContactPhone"
key={`movingContactPhone:${movingContactPhone || userPhone}`}
defaultValue={movingContactPhone || userPhone}
required={true}
/>
{userName
? undefined
: (
<input
type="password"
className={classes.GatherContactInput}
placeholder="Password"
name="userPassword"
required={true}
autoComplete="new-password"
/>
)
}
</div>
</Form>
);
GatherContact.propTypes = {
classes: PropTypes.object.isRequired,
onSubmit: PropTypes.func.isRequired,
movingContactName: PropTypes.string.isRequired,
movingContactEmail: PropTypes.string.isRequired,
movingContactPhone: PropTypes.string.isRequired,
userName: PropTypes.string.isRequired,
userEmail: PropTypes.string.isRequired,
userPhone: PropTypes.string.isRequired
};
export default GatherContact;