React.js可以't更改复选框状态

React.js can't change checkbox state

本文关键字:复选框 状态 js 可以 React      更新时间:2023-09-28

我创建了这个简单的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} />

只为其他来这里的人。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>

这是谷歌上"React Component not updated"的热门话题之一,因此尽管答案已被广泛接受,但我认为这可能会产生误导。

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"——尽管这很有效,但通常只是一个折中方案。