簡體   English   中英

從開關 material-ui 返回是或否

[英]return yes or no from switch material-ui

您好,我正在構建一個表單,我能夠使用我的 onchange 和 state 返回我的其他輸入的值。但是當我嘗試實現開關時,我什么都得不到,甚至連真或假都沒有。 我如何讓開關在切換時返回是或否標簽? 這是我將使用的 material-ui 組件

材料.js

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import FormGroup from '@material-ui/core/FormGroup';
import Switch from '@material-ui/core/Switch';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';


export default function CustomizedSwitches() {

  return (
<FormGroup>
  <Typography component="div">
    <Grid component="label" container alignItems="center" spacing={1}>
      <Grid item>No</Grid>
      <Grid item>
        <AntSwitch />
      </Grid>
      <Grid item>Yes</Grid>
    </Grid>
  </Typography>
</FormGroup>
);
}

這是我處理表單輸入的方式

表單.js

class App extends Component {

// constructor
  constructor(props) {
    super(props);


    // initial state
    this.state = {
        formValues                : {},//this is where i store my input values
    };

 // i use this to submit info
this.submitInformation        = this.submitInformation.bind(this);

  }


  handleChange(event) {
    event.preventDefault();
    const isCheckbox = event.target.type==='checkbox'; //implementing this does not work why??


    let formValues = this.state.formValues
    let name = event.target.name;
    let value = isCheckbox ? event.target.checked : event.target.value; //is the problem here??

    formValues[name] = value

    this.setState({formValues});
  }



 async submitInformation(event){

    event.preventDefault();
    alert('You have submitted the form.')

    let sharePointStructure = {
        response                                     : this.state.formValues[false],
        ToolName                                  : this.state.formValues["ToolName"],
}


  return (
  <div className="App">
    <div >

      <form className="float-container" onSubmit = {this.submitInformation}>

          <div>
             
              <CustomizedSwitches 
              name="response" 
              onChange={this.handleChange.bind(this)} 
              checked={this.state.formValues["response"]}/>
          </div>
       <form/>
    </div>

)

你正在改變 state 這可能會導致一些問題。 通過制作 state 的淺表副本來嘗試此操作:

handleChange(event) {
    event.preventDefault();
    const isCheckbox = event.target.type==='checkbox'; //implementing this does not work why??


    let formValues = {...this.state.formValues} //make a shallow copy of formValues
    let name = event.target.name;
    let value = isCheckbox ? event.target.checked : event.target.value; //is the problem here??

    formValues[name] = value // then mutate the copied state

    this.setState({formValues});
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM