vendredi 23 décembre 2016

ReactJs checkbox being updated one click too late and values reversed

I have a large form with various form elements which is dynamically rendered from a get request. All other types of form (such as text and select) are working fine, however the checkbox is not.

First of all, it's event handler only fires the event when I click twice (ignoring the first time). Secondly it is 'reversed' (says 'on' when unchecked, but 'off' when checked). Also, why is it giving me on and off? I would like it to give me true and false.

What can I do to fix these?

Here is my current relevant code:

class Input extends Component{
    render(){
        var form;
        if (this.props.componentClass=="choice") {
            // select form
        }

        else if (this.props.componentClass=="bool")
            form =(<Checkbox id={this.props.controlId} onChange={this.props.onChange}
                               defaultChecked={this.props.placeholder} >
                        </Checkbox>);
        else
            // text form
        return (
            <div>
                <Form inline onSubmit={this.handleSubmit}>
                    <FormGroup controlId={this.props.controlId}>
                        <ControlLabel>{this.props.name}</ControlLabel>
                        {form}
                        <Panel>
                        {this.props.description}
                        </Panel>
                        <FormControl.Feedback />
                    </FormGroup>
                </Form>
                <br/>
            </div>
        );
    }
}

// onChange code (comes from a parent component)
    onChange(e){
        const form = Object.assign({}, this.state.form);
        form[e.target.id] = e.target.value;
        this.setState({ form });
        console.log('current state: ', this.state);
    }




Aucun commentaire:

Enregistrer un commentaire