Add text to Switch formcontrol and change it in toggle using material ui

孤人 提交于 2020-08-09 09:01:07

问题


I am using Material UI's Switch component and I want to add text inside it. Also I need to make it square in shape.

How to I add text inside the Switch component. It should say on when selected and off when default. I am using Material UI's Switch inside Formcontrol in reactjs form.

<FormControlLabel 
  label="Private ? "
  labelPlacement="start"
  control={
    <Switch
       checked={this.state.checked}
       onChange={this.handleChange}
       color='primary'
    />
  } 
/>

回答1:


Here is an example of how to change the text based on the state of the Switch as well as the styles for a square 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);



来源:https://stackoverflow.com/questions/56128013/add-text-to-switch-formcontrol-and-change-it-in-toggle-using-material-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!