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中获得“已完成”的状态。 我应该创建一个空对象以接收复选框状态吗?感谢您的帮助。
答案 0 :(得分:1)
onChange函数应如下所示:
(event) => this.props.handleChange(event.value)
我不确定event.value
,但记录该事件,并且复选框值应在其中。