无法读取未定义的属性"句柄更改"



我是新手。我犯了上面的错误。我做错了什么

这是我的代码:

import React from "react"
import ReactDOM from "react-dom"
import toDoLists from "./components/Array"

class Main extends React.Component {
render(){
return (
<p>
<input type="checkbox" checked={this.props.completed} onChange={function(props){
this.props.handleChange(this.props.id)
}}
/>
{this.props.task}
</p>
)
}
}
class App extends React.Component {
constructor(){
super()
this.state ={
todos: toDoLists
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(id) {
console.log("Changed", id)
}
render() {
const todoItems = this.state.todos.map(function(item){
return(
<Main
key={item.id} task={item.task} completed={item.completed} id={item.id}
handleChange={this.handleChange}
/>
)

})
return (
<div className="col-md-4 bg-dark container mt-5 p-3">
{todoItems}
</div>

)
}
}
ReactDOM.render(
<App/>, document.getElementById("root")
)
import React from "react";
import ReactDOM from "react-dom";
import toDoLists from "./components/Array"

class Main extends React.Component {
render() {
return (
<p>
Hai
<input
type="checkbox"
checked={this.props.completed}
onChange={props => {
this.props.handleChange(this.props.id);
}}
/>
{this.props.task}
</p>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
todos: toDoLists
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(id) {
console.log("Changed", id);
}
render() {
const todoItems = this.state.todos.map(item => {
return (
<Main
key={item.id}
task={item.task}
completed={item.completed}
id={item.id}
handleChange={this.handleChange}
/>
);
});
return (
<div className="col-md-4 bg-dark container mt-5 p-3">{todoItems}</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));

在事件函数内部,该值是未定义的。否则,您将把这个实例传递给选定的函数。你可以使用箭头功能

onChange={props => {
this.props.handleChange(this.props.id);
}}

问题出现在App组件声明中。一个扩展React.Component的类在构造函数中接收props,您必须将变量props传递给super()才能正确调用Parent的类(React.Cmponent(,类似于以下内容:

constructor(props) {
super(props);
//Continue with your state/binding
}

我还看到.map内部有一个问题,要么绑定该函数

const todoItems = this.state.todos.map(function(item){
return(
<Main
key={item.id}
task={item.task}
completed={item.completed}
id={item.id}
handleChange={this.handleChange}
/>
)
}.bind(this))
//rest of your code

或者更好的是,使用箭头函数。

const todoItems = this.state.todos.map((item) => (
<Main
key={item.id}
task={item.task}
completed={item.completed}
id={item.id}
handleChange={this.handleChange}
/>
));
//rest of your code

渲染组件时,请执行以下操作:handleChange={(id) => this.handleChange(id)},当您想在该组件中运行函数时,请执行this.props.handleChange(this.props.id)

最新更新