Вопрос

I'm trying to reproduce a simple two-way binding example in the React.js framework by following this official tutorial: "Two-Way Binding Helpers".

I created a "MyCheckbox" component that looks like this:

var MyCheckbox = React.createClass({

    mixins: [React.addons.LinkedStateMixin],

    getInitialState: function () {
        return {
            fieldname: '',
            value: this.props.value
        };
    },

    render: function () {
        var valueLink = this.linkState('value');
        var me = this;
        var handleChange = function (e) {
            valueLink.requestChange(e.target.value === 'on');
        };

        return React.DOM.input({
            type: 'checkbox',
            checked: valueLink.value,
            onChange: handleChange,
        });
    }

});

"MyCheckbox" is rendered the following way:

React.renderComponent(MyCheckbox({
    value: false
}), document.body);

When rendering the first time, everything works as expected, if the value is true, the checkbox will be checked, if the value is false then it will not.

If you initialise the checkbox as being unchecked and then check it, everything works fine.

Any ideas ?

I use the latest React.js version (v0.10.0).

Это было полезно?

Решение

The "value" property on a checkbox is fixed, in the old days it was the value that was submitted along with the form only if the checkbox was checked.

The quick fix is this instead:

valueLink.requestChange(e.target.checked);

The valueLink only works when it is the value of the input that changes. Turns out that to link to the checked property, the checkedLink needs to be used instead:

render: function () {
    return React.DOM.div(null, [
        React.DOM.input({
            type: 'checkbox',
            checkedLink: this.linkState('value'),
        }),
        React.DOM.span(null, "state: " + this.state.value)
    ]);
}

Seems a shame that the valueLink can't be used for both!

Другие советы

One simple solution using state:

  constructor(props) { // list of objects
    super(props);
    this.state = {
      is_checked: false
    };
  }

  toggleCheckbox(event) {
    let newValue = (this.state.is_checked === "on" || this.state.is_checked === true) ? false : true;
    this.setState({
      is_checked: newValue
    });
  }

  render() {
    return (
      <div>
        <input type="checkbox" checked={this.state.is_checked}
          onChange={this.toggleCheckbox.bind(this)}
        />
      </div>
    );
  }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top