简体   繁体   中英

Boolean checkbox value in JSX doesn't work

IU'm using a github code example and that works perfectly with text inputs & numbers, but when I want to use checkbox inputs, the application doesn't understand the values and returns null or just on values...

Any idea why this doesn't work on fEdit function?

import React, { Component } from "react";
// import './App.css';
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "React Simple CRUD Application",
      act: 0,
      index: "",
      datas: []
    };
  }

  componentDidMount() {
    this.refs.name.focus();
  }

  handleChange = e => {
    console.log(e.target.value);
  };

  fSubmit = e => {
    e.preventDefault();
    console.log("try");

    let datas = this.state.datas;
    let name = this.refs.name.value;
    let isenable = this.refs.isenable.value;

    if (this.state.act === 0) {
      //new
      let data = {
        name,
        isenable
      };
      datas.push(data);
      console.log(data.isenable);
    } else {
      //update
      let index = this.state.index;
      datas[index].name = name;
      datas[index].isenable = isenable;
    }

    this.setState({
      datas: datas,
      act: 0
    });

    this.refs.myForm.reset();
    this.refs.name.focus();
  };

  fRemove = i => {
    let datas = this.state.datas;
    datas.splice(i, 1);
    this.setState({
      datas: datas
    });

    this.refs.myForm.reset();
    this.refs.name.focus();
  };

  fEdit = i => {
    let data = this.state.datas[i];
    this.refs.name.value = data.name;
    this.refs.isenable.value = data.isenable;

    this.setState({
      act: 1,
      index: i
    });

    this.refs.name.focus();
  };

  render() {
    let datas = this.state.datas;
    return (
      <div className="App">
        <h2>{this.state.title}</h2>
        <form ref="myForm" className="myForm">
          <input
            type="text"
            ref="name"
            placeholder="your name"
            className="formField"
          />
          <input
            type="checkbox"
            ref="isenable"
            placeholder="your isenable"
            className="formField"
          />
          <button onClick={e => this.fSubmit(e)} className="myButton">
            submit
          </button>
        </form>
        <pre>
          {datas.map((data, i) => (
            <li key={i} className="myList">
              {data.name} - {(data.isenable || false).toString()}
              <button onClick={() => this.fRemove(i)} className="myListButton">
                remove
              </button>
              <button onClick={() => this.fEdit(i)} className="myListButton">
                edit
              </button>
            </li>
          ))}
        </pre>
      </div>
    );
  }
}

export default App;

When working with checkboxes, refer to the checked property not the value. This is the true or false state of the checkbox.

In fSubmit :

let isenable = this.refs.isenable.checked;

In fEdit :

this.refs.isenable.checked = data.isenable;

In the render:

{data.name} - {data.isenable ? 'on' : 'off'}

Working demo

Complete code with fixes:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "React Simple CRUD Application",
      act: 0,
      index: "",
      datas: []
    };
  }

  componentDidMount() {
    this.refs.name.focus();
  }

  handleChange = e => {
    console.log(e.target.value);
  };

  fSubmit = e => {
    e.preventDefault();
    console.log("try");

    let datas = this.state.datas;
    let name = this.refs.name.value;
    let isenable = this.refs.isenable.checked;

    if (this.state.act === 0) {
      //new
      let data = {
        name,
        isenable
      };
      datas.push(data);
      console.log(data.isenable);
    } else {
      //update
      let index = this.state.index;
      datas[index].name = name;
      datas[index].isenable = isenable;
    }

    this.setState({
      datas: datas,
      act: 0
    });

    this.refs.myForm.reset();
    this.refs.name.focus();
  };

  fRemove = i => {
    let datas = this.state.datas;
    datas.splice(i, 1);
    this.setState({
      datas: datas
    });

    this.refs.myForm.reset();
    this.refs.name.focus();
  };

  fEdit = i => {
    let data = this.state.datas[i];
    this.refs.name.value = data.name;
    this.refs.isenable.checked = data.isenable;

    this.setState({
      act: 1,
      index: i
    });

    this.refs.name.focus();
  };

  render() {
    let datas = this.state.datas;
    return (
      <div className="App">
        <h2>{this.state.title}</h2>
        <form ref="myForm" className="myForm">
          <input
            type="text"
            ref="name"
            placeholder="your name"
            className="formField"
          />
          <input
            type="checkbox"
            ref="isenable"
            placeholder="your isenable"
            className="formField"
          />
          <button onClick={e => this.fSubmit(e)} className="myButton">
            submit
          </button>
        </form>
        <pre>
          {datas.map((data, i) => (
            <li key={i} className="myList">
              {data.name} - {data.isenable ? 'on' : 'off'}
              <button onClick={() => this.fRemove(i)} className="myListButton">
                remove
              </button>
              <button onClick={() => this.fEdit(i)} className="myListButton">
                edit
              </button>
            </li>
          ))}
        </pre>
      </div>
    );
  }
}

Sidenote: I wouldn't use Refs in this case. Take a look at the docs, you can see when to use Refs and when not to. The Forms docs cover how to handle forms without Refs.

You should use the checked attribute of the isenable element to determine whether the checkbox is checked and put this value in your form. You can check the mdn docs: https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/checkbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM