【问题标题】:Add text to Switch formcontrol and change it in toggle using material ui将文本添加到 Switch formcontrol 并使用材质 ui 在切换中更改它
【发布时间】:2019-05-14 10:12:28
【问题描述】:
我正在使用 Material UI 的 Switch 组件,我想在其中添加文本。我还需要把它做成方形。
如何在 Switch 组件中添加文本。它应该在选择时显示打开,默认时显示关闭。我在 reactjs 表单中的 Formcontrol 中使用 Material UI 的 Switch。
<FormControlLabel
label="Private ? "
labelPlacement="start"
control={
<Switch
checked={this.state.checked}
onChange={this.handleChange}
color='primary'
/>
}
/>
【问题讨论】:
标签:
reactjs
switch-statement
material-ui
slidetoggle
【解决方案1】:
以下是如何根据 Switch 的状态以及方形 Switch 的样式更改文本的示例:
import React from "react";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Switch from "@material-ui/core/Switch";
import { withStyles } from "@material-ui/core/styles";
const styles = {
// use "icon" instead of "thumb" in v3
thumb: {
borderRadius: 0
}
};
class SwitchLabels extends React.Component {
state = {
checked: true
};
handleChange = event => {
this.setState({ checked: event.target.checked });
};
render() {
return (
<FormControlLabel
control={
<Switch
classes={this.props.classes}
checked={this.state.checked}
onChange={this.handleChange}
value="checked"
color="primary"
/>
}
labelPlacement="start"
label={this.state.checked ? "On" : "Off"}
/>
);
}
}
export default withStyles(styles)(SwitchLabels);