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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28478945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:50:53  来源:igfitidea点击:

React.js can't change checkbox state

javascriptreactjs

提问by Bazinga

I created this simple TODO list, and when I want to check the checkbox I can't.

我创建了这个简单的待办事项列表,当我想选中复选框时,我不能。

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;

The parent:

家长:

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;

回答by Henrik Andersson

When you haven't specified an onChangehandler on your inputs React will render the input field as read-only.

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

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

and

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

回答by Chris

This is one of the top hits on Google for "React Component not updating", so although the answer has been well accepted, I think it could be misleading.

这是 Google 上“React 组件未更新”的热门话题之一,因此尽管答案已被广泛接受,但我认为它可能具有误导性。

The checkboxtype doesn't require the onChange. I am not sure if this has changed since the answer was posted (current version of React is v15 - 2016-04-20).

checkbox类型不需要onChange. 我不确定自从答案发布后这是否已经改变(React 的当前版本是 v15 - 2016-04-20)。

See the following example of it working without an onChange handler (see JSBIN):

请参阅以下示例,它在没有 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);

Another side note - a lot of answers (for similar questions) simply recommend "defaultChecked" - although this works, it is usually a half measure.

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

回答by muuvmuuv

Just for others coming here. React now provides 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>