Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

javascript - React.js can't change checkbox state

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;
question from:https://stackoverflow.com/questions/28478945/react-js-cant-change-checkbox-state

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

and

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...