ReactJS复选框默认值

时间:2019-03-11 18:49:38

标签: reactjs checkbox

我在将复选框设置为在加载时就选中时遇到问题,该复选框始终由用户使用ReactJS进行选择。我现在还很陌生,现在我在这种事情上挣扎很多。

我的代码就是这样

import DbCheckbox2 from 'modules/Checkbox-Checked'

const GenerateTemplateComponent = ({
  handleSubmit,
  handleCancel,
  classes
}) => {
  return (
    <Form
      onSubmit={handleSubmit}
      validate={validate}
      render={({ handleSubmit, invalid, pristine, form: { change } }) => (
        <form className={classes.form} onSubmit={handleSubmit}>
          <PanelBody>
            <Grid container>
              <Grid item xs={12} md={12}>
                <Field
                  name='name'
                  component={DbInputField}
                  required
                  label={<FormattedMessage id='offre-name' />}
                />
              </Grid>
              <Grid container>
                <Grid item xs={6} md={6}>
                  <Field
                    //className={classes.inputCheckbox}
                    name='section'
                    component={DbCheckbox2}
                    type='checkbox'
                    color='primary'
                    label={<FormattedMessage id='offre-section' />}  
                  />
                </Grid>

Checkbox-Checked 文件上,就像这样

import React from 'react'

import FormControl from '@material-ui/core/FormControl'
import FormControlLabel from '@material-ui/core/FormControlLabel'
import Checkbox from '@material-ui/core/Checkbox'

const DbCheckbox2 = ({
  label,
  className,
  checked=true,
  value=true,
}) => (
  <FormControl className={className} component="fieldset">
    <FormControlLabel
      control={
        <Checkbox
          checked={checked}
          value={value}
        />
      }
      label={label}
    />
  </FormControl>
)

export default DbCheckbox2

我尝试在字段属性上添加 value =“ true” ,并且在html上获得了value =“ true”,但是当我再次单击时,它确实为我带来了我想要的结果在复选框上,就像第一次无法识别一样。也许他正在等待onclick事件或其他事件,但我根本不了解。有帮助吗?

1 个答案:

答案 0 :(得分:0)

这向您展示了如何处理复选框中的选中状态:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { checkbox1: true };
    this.handleChange = this.handleChange.bind(this);
  }
  
  handleChange(e) {
      const element = e.target;
      this.setState({
          [element.name]: element.checked
      });
  }
  
  render() {
    return (
        <input
         type="checkbox"
          name='checkbox1'
          checked={this.state.checkbox1}
          onChange={ this.handleChange }/>
      )
  }
}

ReactDOM.render( < App / > ,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<div id="root" />