vendredi 1 janvier 2016

react: get custom checkbox's checked attribute

I want to so some customization with checkbox, it can look like this:

enter image description here

so I wrap my custom checkbox into a React Component:

require('../../less/ck-checkbox.less');
var React = require('react');

var CkCheckbox = React.createClass({
    propTypes: {
        name: React.PropTypes.string,
        text: React.PropTypes.string,
        defaultChecked: React.PropTypes.bool,
        onChange: React.PropTypes.func
    },

    getDefaultProps: function() {
        return {
            name: 'checkbox',
            text: '',
            defaultChecked: false,
            onChange: function () {}
        };
    },

    render: function() {
        return (
            <div className="ck-checkbox">
                <label>
                    <input type="checkbox" name={this.props.name} ref="c" defaultChecked={this.props.defaultChecked} onChange={this.props.onChange.bind(this, this.refs.c.checked)}/>
                    <span className="icons">
                        <span className="icon-checked-o icon-true"></span>
                        <span className="icon-circle-o icon-false"></span>
                    </span>
                    {this.props.text.length > 0 ?
                    <span className="ck-checkbox-text">{this.props.text}</span> : null
                    }
                </label>
            </div>
            );
    }
});

module.exports = CkCheckbox;

and my container is like this:

var React = require('react');

var CkCheckbox = require('./CkCheckbox.js');

var Test = React.createClass({
    render: function() {
        return (
            <div>
                <CkCheckbox onChange={this._handleChange}/>
            </div>
            );
    },

    _handleChange: function(checked, e) {
        console.log(checked)
    }
});

module.exports = Test;

you can see that, I tried to bind this.refs.c.checked in the onChange callback, but it doesn't work.

so, how can I get the checked state of my custom checkbox in Test component in the _handleChange function?




Aucun commentaire:

Enregistrer un commentaire