简体   繁体   中英

Checkbox don't show checked

I'm working with checkbox input. When I click on checbox, checkbox don't show checked but checkbox's value I still get. I use React JS

Simple checkbox

import React from 'react';
import callApi from './../../utils/apiCaller'
import { Link } from 'react-router-dom'


class ProductActionPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: '',
            productStatus: ''
        }
    }

    onChange = (e) => {
        var target = e.target;
        var name = target.name;
        var value = target.type === 'checkbox' ? target.checked : target.value;
        this.setState({
            [name]: value
        });
    }

    render() {
        var statusCheckbox = this.state.productStatus === 'true' ? true : false;
        return (
            <div className="row">
                <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6">
                        <div className="form-group">
                            <label>Trang thai: </label>
                        </div>
                        <div className="checkbox">
                            <label>
                                <input type="checkbox" checked={statusCheckbox} name="productStatus" onChange={this.onChange} />
                                Con hang
                            </label>
                        </div>
                        <button type="submit" className="btn btn-primary">Luu lai</button>
                        <Link to="/product/list" className="btn btn-danger ml-5">Huy bo</Link>
                </div>
            </div>
        );
    }

}

How can I show checked checkbox?

this.state.productStatus is a boolean value, so your condition will always give you the false , because you are comparing Boolean === String .

Just change

var statusCheckbox = this.state.productStatus === 'true' ? true : false;

to

var statusCheckbox = this.state.productStatus ? true : false;   //It doesn't make any sense

Or simply

var statusCheckbox = this.state.productStatus;

Or you can directly use this.state.productStatus ,

<input 
   type="checkbox" 
   checked={this.state.productStatus} 
   name="productStatus" 
   onChange={this.onChange} 
/>

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