英文:
What's wrong with my following react Js code?
问题
import React from "react";
import Header from "./Header";
import ToDoItem from "./ToDoItem";
import toDoData from "./toDoData";
class App extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(id) {
console.log("Id value: ", id);
}
render() {
const toDoTasks = toDoData.map((toDos) => (
<ToDoItem
key={toDos.id}
handleChange={this.handleChange} // Line 26
/>
));
return (
<div className="rootComponent">
<Header />
{toDoTasks}
</div>
);
}
}
export default App;
英文:
import React from "react"
import Header from "./Header"
import ToDoItem from "./ToDoItem"
import toDoData from "./toDoData"
class App extends React.Component{
constructor(props){
super(props)
this.handleChange=this.handleChange.bind(this)
}
handleChange(id){
console.log("Id value : ",id)
}
render(){
const toDoTasks = toDoData.map(function (toDos){
return <ToDoItem
key={toDos.id}
handleChange={this.handleChange} // Line 26
/>
})
return(
<div className="rootComponent">
<Header />
{toDoTasks}
</div>
)
}
}
export default App
Error
TypeError: this is undefined
render/toDoTasks<
src/components/App.js:26
Here in my code I'm trying to attach my handleChange
function to my <ToDoItem />
component.But here I'm unable call handleChange
function.If I define the function inside the constructor then I can call the function but I dont want my function inside the constructor.How can I do this.
答案1
得分: 2
问题出在这里
const toDoTasks = toDoData.map(function (toDos){
return <ToDoItem
key={toDos.id}
handleChange={this.handleChange} // Line 26
/>;
})
function (toDos) 创建了一个独立的作用域,因此this不再指向您的类实例。
将其更改为
const toDoTasks = toDoData.map(toDos => <ToDoItem key={toDos.id} handleChange={this.handleChange}/>);
将按预期工作,因为箭头函数保留了父作用域,不会创建自己的作用域。
英文:
The issue is here
const toDoTasks = toDoData.map(function (toDos){
return <ToDoItem
key={toDos.id}
handleChange={this.handleChange} // Line 26
/>
})
function (toDos) creates a separate scope and this no longer refers to your class instance.
Changing that to
const toDoTasks = toDoData.map(toDos => <ToDoItem key={toDos.id} handleChange={this.handleChange}/>);
will work as expected, as arrow functions retain the parent scope and don't create their own.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论