我无法从检查清单的handleChange函数获得状态

时间:2019-05-24 13:17:33

标签: react-native

一般而言,我是React和Javascript中的一种新功能。我正在尝试使用复选框进行核对。在前端,它或多或少地起作用。我的问题是,我正在尝试获取任务是否完成的状态。我已经创建了一个带有对象的数组(请参见MainContent代码),但是当我单击复选框时,它会在console.log中返回“ undefined”。

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

应用组件

import React, { Component } from "react";
import Header from "./components/Header";
import MainContent from "./components/MainContent";

import "./styles.css";

class App extends Component {
  render() {
    return (
      <div className="App">
        <Header />
        <MainContent />
      </div>
    );
  }
}

export default App;

MainContent组件

import React, { Component } from "react";

import task from "../assets/task";
import ListItem from "../components/ListItem";

class MainContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      task: [
        {
          id: 1,
          task: "task 01",
          name: "pedro",
          completed: null
        },
        {
          id: 2,
          task: "task 02",
          completed: null
        },
        {
          id: 3,
          task: "task 03",
          completed: null
        }
      ]
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange = completed => {
    alert("your task is", completed);
    console.log("This task is", completed);
  };

  render() {
    console.log("task render", this.task);

    const taskComponents = this.state.task.map(data => (
      <ListItem
        key={data.id}
        task={data.task}
        id={data.id}
        completed={data.completed}
        handleChange={() => {
          this.handleChange();
        }}
      />
    ));
    return <div>{taskComponents}</div>;
  }
}

export default MainContent;

ListItem组件

import React, { Component } from "react";
let i = 1;

class ListItem extends Component {
  render() {
    return (
      <div className="ListItem">
        <p style={{ color: i % 2 ? "black" : "orange" }}>
          <input
            type="checkbox"
            checked={this.props.completed}
            onChange={() => this.props.handleChange(this.props.completed)}
          />
          Task {i++}: <b>{this.props.task}</b>
        </p>
      </div>
    );
  }
}

export default ListItem;

我希望从handleChange中获得“已完成”的状态。 我应该创建一个空对象以接收复选框状态吗?感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

onChange函数应如下所示:

(event) => this.props.handleChange(event.value)

我不确定event.value,但记录该事件,并且复选框值应在其中。