React.js 无法更改复选框状态

React.js can't change checkbox state

我创建了这个简单的 TODO 列表,但当我想勾选复选框时却做不到。

import React from 'react';

const TodoItem = React.createClass({

  render() {
    return (
      <div>

        <span>{this.props.todo}</span>
        <input type="checkbox" checked={this.props.done} />

      </div>
    );
  }

});

export default TodoItem;

家长:

import React from 'react';
import TodoItem from './TodoItem';
import AddTodo from './AddTodo';

const TodoList = React.createClass({

  getInitialState() {
    return {
      todos: [{
        todo: 'some text',
        done:false
      },{
        todo: 'some text2',
        done:false
      },
      {
        todo: 'some text3',
        done:true
      }]
    };
  },

   addTodo (childComponent) {
    var todoText = childComponent.refs.todoText.getDOMNode().value;
    var todo = {
      todo: todoText,
      done:false
    };
    var todos = this.state.todos.concat([todo]);
    this.setState({
      todos:todos
    });

    childComponent.refs.todoText.getDOMNode().value = '';
  },

  render() {

    var Todos = this.state.todos.map(function(todo) {
      return (
           <TodoItem todo={todo.todo} done={todo.done} />
        )
    });

    return (
      <div>
       {Todos}
       <AddTodo addTodo={this.addTodo}/>
      </div>

    );
  }

});

export default TodoList;

如果您没有在输入上指定 onChange 处理程序,React 会将输入字段呈现为只读。

getInitialState() {
    return {
        done: false
    };
}

<input type="checkbox" checked={this.state.done || this.props.done } onChange={this.onChange} />

这是 Google 上 "React Component not updating" 的热门点击之一,因此尽管答案已被广泛接受,但我认为它可能具有误导性。

checkbox 类型不需要 onChange。我不确定自发布答案以来这是否发生了变化(React 的当前版本是 v15 - 2016-04-20)。

请参阅以下没有 onChange 处理程序的工作示例(请参阅 JSBIN):

class Checky extends React.Component {
    render() {
      return (<input type="checkbox" checked={this.props.checked} />);
    }
}

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = { checked: true };
    }

    render() {
        return (
          <div>
            <a href="#" onClick={ () => { this.setState({ checked: !this.state.checked }); }}>Toggle</a>
            <hr />
            <Checky checked={this.state.checked} />
          </div>
        );
    }
}


React.render(<App />, document.body);

另一个旁注-很多答案(针对类似问题)只是推荐"defaultChecked"-虽然这有效,但通常是一半的措施。

仅供来此的其他人使用。 React 现在提供 defaultChecked:

<label htmlFor={id}>
  <input
    id={id}
    type="checkbox"
    defaultChecked={input.props.checked}
    // disabled={input.props.disabled}
  />
  <span className="custom-checkbox"></span>
  {restChildren}
</label>