【问题标题】:Cannot read property 'checked' of undefined React无法读取未定义 React 的属性“已检查”
【发布时间】:2026-02-15 05:30:01
【问题描述】:

我正在制作一个小应用程序(主题列表),我在其中使用复选框删除一些主题,但是当我启动应用程序时,控制台说“无法读取未定义的属性‘已检查’”我在一些帖子上读到它可能是因为我重写了复选框,但我看不到在哪里。

你能帮忙吗?

import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Topics } from '../api/topic.js';
import Topic from './Topic.jsx';

class AppTopic extends Component {

  toggleChecked() {
      // Set the checked property to the opposite of its current value
      Topics.update(this.props.topic._id, {
        $set: { checked: !this.props.topic.checked },
      });
    }

    deleteThisTopic() {
      Topics.remove(this.props.topic._id);
    }

  renderTopics() {
    return this.props.topics.map((topic) => (
      <Topic key={topic._id} topic={topic} />
    ));
  }

  render() {

    // Give tasks a different className when they are checked off,
    // so that we can style them nicely in CSS
    const topicClassName = this.props.topic.checked ? 'checked' : '';

      return (

        <li className={topicClassName}>
        <button className="delete" onClick={this.deleteThisTopic.bind(this)}>
          &times;
        </button>

        <input
          type="checkbox"
          readOnly
          checked={this.props.topic.checked}
          onClick={this.toggleChecked.bind(this)}
        />
        <span className="text">{this.renderTopics()}</span>
      </li>
      );

    }
  }

  AppTopic.propTypes = {
  topics: PropTypes.array.isRequired
};


export default createContainer(() => {
  return {
    topics: Topics.find({}).fetch(),
  };
}, AppTopic);

【问题讨论】:

  • @Kinduser 父类?
  • 无论如何,这是不可读的。尽量避免使用类似的变量名称,例如Topictopic。并为组件使用单独的文件。

标签: reactjs checkbox typeerror


【解决方案1】:

这里是 ../api/topic.js

import { Mongo } from 'meteor/mongo';

export const Topics = new Mongo.Collection('topics');

和./Topic.jsx

import React, { Component, PropTypes } from 'react';
import { Topics } from '../api/topic.js';


export default class Topic extends Component {
  render() {
    return (
      <div>
        <li>{this.props.topic.text}  ARN:  {this.props.topic.arn} <button>S'inscrire</button></li>
      </div>
  );
  }
}

Topic.propTypes = {

  topic: PropTypes.object.isRequired,
};

【讨论】:

  • 我找到了一个更简单的方法可以做到这一点
最近更新 更多