【发布时间】:2019-07-22 15:24:41
【问题描述】:
我正在使用Material UI 创建一个表单。该表格有两个部分。一个是用户的收货地址,另一个是帐单地址。在许多情况下,后者与前者相同,因此我提供了一个复选框来自动填写账单地址和送货地址。它通过调用一个函数来将要更新的字段的值设置为等于另一个字段的值,该值保存在 React 状态中。
MUI Input 组件自己处理字段。 InputLabel 组件也用于标记它们。通常,当在字段中输入值时,InputLabel 文本会像这样移动到字段上方:
However, when the checkbox is checked and the value is populated in the billing address field by typing in the shipping address field, the label fails to get out of the way:
我一直无法解决问题,而且 Stack Overflow 上没有类似的问题似乎可以解决我的问题。我该如何解决这个问题?
编辑:
这是截图中的代码:
<Grid container spacing={40} className={classes.formContainer}>
<Grid item xs>
</Grid>
<Grid item xs>
<FormControlLabel
control={
<Checkbox
checked={this.state.sameAddressScreen2}
onChange={this.handleSameAddressScreen2}
value="sameAddressScreen2"
/>
}
label="Same as Location Address"
/>
</Grid>
</Grid>
<Grid container spacing={40} className={classes.formContainer}>
<Grid item xs={6}>
<FormControl margin="normal" required fullWidth>
<InputLabel htmlFor="locationStreetAddress1">Street Address 1</InputLabel>
<Input id="locationStreetAddress1" name="locationStreetAddress1" autoFocus value={this.state.locationStreetAddress1} onChange={this.handleChange} />
</FormControl>
</Grid>
<Grid item xs={6}>
<FormControl margin="normal" required fullWidth>
<InputLabel htmlFor="mailingStreetAddress1">Street Address 1</InputLabel>
<Input id="mailingStreetAddress1" name="mailingStreetAddress1" autoFocus value={sameValue('mailingStreetAddress1')} onChange={this.handleChange} />
</FormControl>
</Grid>
</Grid>
这是代码调用的状态和 sameValue 函数:
state = {
locationStreetAddress1: '',
mailingStreetAddress1: '',
sameAddressScreen2: false,
};
sameValue = (field) => {
if (this.state.sameAddressScreen2 === true) {
let stateKey = 'location'.concat(field.slice(7));
return this.state[stateKey];
} else {
return this.state[field];
}
}
【问题讨论】:
-
请分享一个CodeSandbox 或类似的可以重现问题并将该代码包含在您的问题文本中的代码。
-
我已将相关代码添加到我原来的问题中。
-
InputLabel 组件有一个名为“shrink”的属性 - 当 Input 组件有值时将其设置为 true,您将获得所需的行为。
-
这一切对我来说都很好,无需在这里明确管理
shrink:codesandbox.io/s/1pl738n94 -
状态管理方法不会对 Material-UI 产生任何影响。看看你是否可以修改我的沙箱以更接近你正在做的事情,看看你是否可以重现这个问题。您使用的是最新版本的 Material-UI (3.9.2) 吗?
标签: reactjs forms material-ui