reactjs - Material UI Switch onChange 处理程序不起作用
问题描述
我已经实现了两个材质 ui 开关,它们应该更新状态中的属性,但是它们的 onChange 处理程序似乎不起作用,因为属性没有得到更新(但是我能够翻转开关的控件)。预期的行为是当我打开/关闭开关并单击保存时,状态中的属性会发生变化。有关开关 api 的参考,请访问此链接 - https://material-ui.com/components/switches/#Switches.js
这是我已经实施的。
export class SwitchNotifications extends React.Component {
constructor(props) {
super(props);
this.state = {
email_notification_enabled: false,
app_notification_enabled: false
};
}
componentDidMount() {
const token = localStorage.getItem("token");
let detail = details(token);
this.props.dispatch(fetchProfile(detail.username));
}
componentWillReceiveProps(nextProps) {
this.setState({
email_notification_enabled: nextProps.profile.email_notification_enabled,
app_notification_enabled: nextProps.profile.app_notification_enabled
});
}
handleChangeEmailNotification = event => {
this.setState({ email_notification_enabled: event.target.checked });
};
handleChangeAppNotification = event => {
this.setState({ app_notification_enabled: event.target.checked });
};
handleSubmit = event => {
event.preventDefault();
const new_profile = {
email_notification_enabled: this.state.email_notification_enabled,
app_notification_enabled: this.state.app_notification_enabled
};
let data = { profile: new_profile };
this.props.dispatch(updateProfileAction(this.state.username, data));
};
render() {
const {
app_notification_enabled,
email_notification_enabled
} = this.state;
return (
<div>
<br />
<div className="containers">
<div className="upload-profile-form edit-upload-course-form">
<img id="member-img" src={image} />
<br />
<Grid container spacing={3}>
<Grid item xs={12}>
<FormControlLabel
control={
<Switch
checked={app_notification_enabled}
onChange={this.handleChangeAppNotification}
value={app_notification_enabled}
inputProps={{ "aria-label": "secondary checkbox" }}
/>
}
label="App notifications"
/>
</Grid>
<Grid item xs={12}>
<FormControlLabel
control={
<Switch
checked={email_notification_enabled}
onChange={this.handleChangeEmailNotification}
value={email_notification_enabled}
color="primary"
inputProps={{ "aria-label": "primary checkbox" }}
/>
}
label="Email notifications"
/>
</Grid>
<Grid item xs={12}>
<button
onClick={this.handleSubmit}
className="submit-profile-button"
>
{" "}
SAVE
</button>
</Grid>
</Grid>
</div>
</div>
</div>
);
}
}
解决方案
推荐阅读
- c# - 有没有办法通过 bot 框架中的 CSS 或 C# 更改 webchat 中的字体大小?
- excel - 结合使用 OR 和 AND
- java - 内存数据库,用于集成测试,调用 RestTemplate 方法后丢失所有数据
- python - Python - 如何将字符串转换为数组
- c# - Net Core:将真实数据库复制到实体框架 InMemoryDB
- python - 当我使用 jinja 模板发送电子邮件时,css 不起作用
- ansible - 在 Ansible Jinja 模板中,如何转义双引号内的单引号?
- spring - 为什么 Spring 会创建这个太长的唯一 ID 并导致 DDL 错误?
- javascript - React 在数组上创建自己的函数
- apache-spark - Spark SQL中缓存机制的区别