我试图在里面使用 switchHandler 函数this.state.persons.map()但是得到
“无法读取未定义的属性‘switchHandler’”错误
. 但是,如果我在 map 函数之外使用它,则可以访问它。
class App extends Component {
state = {
persons: [
{ name: "Max", age: 28 },
{ name: "Manu", age: 27, child: "My hobbies : racing" },
{ name: "Ron", age: 26 }
]
};
switchHandler = () => {
this.setState({
persons: [
{ name: "Maxii", age: 28 },
{ name: "Manu", age: 27, child: "My hobbies : swiming" },
{ name: "Ron", age: 26 }
]
});
//return "correct";
};
render() {
//let obj = new App();
return (
<div className="App">
<button onClick={this.switchHandler}>Switch Name</button>
{this.state.persons.map(function(data) {
return (
<div>
<Person
clickChild={this.switchHandler}
name={data.name}
age={data.age}
>
{data.child}
</Person> // // Here I'm getting error for switchHandler
</div>
);
})}
<Person name="tag" age="34" clickChild={this.switchHandler}>
just
</Person> // Here switchHandler is working fine
</div>
);
}
}
export default App;
错误:
App.js:34 未捕获的类型错误:无法读取未定义的属性“switchHandler”
叮当猫咪
相关分类