简体   繁体   中英

Controlled and uncontrolled elements in React. _class is changing an uncontrolled input

I have a Checkbox component which is simple checkbox under the hood however styled to my needs, as it has custom 'fake element' which acts as original one.

Checkbox

import React, {Component} from 'react';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import '../../../stylesheets/common/forms/Checkbox.scss';

export default class extends Component {
    constructor(props) {
        super(props);
        this.state = {checked: props.checked};
    }

    toggle() {
        const checked = !this.state.checked;
        this.setState({checked});
    }

    /**
     * custom prop indicates that we want create custom element to toggle checkbox ie. ImageCheckbox
     * 
     */
    render() {
        const {id, className, children, name, custom = false} = this.props;
        const toggle = this.toggle.bind(this);
        return (
            <FormGroup className={`Checkbox ${className}`}>
                <input id={id}
                       name={name}
                       type="checkbox"
                       checked={this.state.checked}
                       onChange={toggle}/>
                {!custom && <div className="fake-checkbox" onClick={toggle}/>}
                <label htmlFor={id}>{ children }</label>
            </FormGroup>
        )
    }
}

As comment says it in code component allows to create a custom 'fake' element inside label to act as toggle for checkbox.

ImageCheckbox:

import React from 'react';
import Checkbox from '../../common/forms/Checkbox';
import '../../../stylesheets/common/forms/ImageCheckbox.scss';

export default props => (
    <Checkbox className="ImageCheckbox" {...props} custom={true}>
        <div className="image"
             style={{backgroundImage: 'url(' + props.href + ')'}}>
            <p>{ props.children }</p>
        </div>
    </Checkbox>
);

It works how I want but when i click ImageCheckbox I get warning in browser:

warning.js:36 Warning: _class is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://facebook.github.io/react/docs/forms.html#controlled-components

Im not sure what I do wrong and should I be concerned about it.

I found answer in Adam's reply React - changing an uncontrolled input .

I've change undefined to false in constructor when prop isn't passed:

constructor(props) {
    super(props);
    const {checked = false} = props;
    this.state = {checked};
}

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