我是React钩子的新手,最近一直在使用useState函数。.在普通javascript中,此代码有效:
const state = {
firstname: "John",
lastname: "Doe",
greeting: function(){
return sayHello(this.firstname,this.lastname)
}
}
const sayHello = (fname,lname)=>{
return `Hello i'm ${fname} ${lname}, nice to meet you!`;
}
console.log(state.greeting()); //outputs "Hello i'm John Doe, nice to meet you!"
但是使用React钩子:
const [state,setState] = useState({
firstName: "John",
lastName: "Doe",
greeting: function(){
return sayHello(this.firstName,this.lastName)
}
})
const sayHello = (fname,lname) => console.log(`Hello i'm ${fname} ${lname}, nice to meet you!`);
const { firstName, lastName, greeting } = state;
return (
<div>
<button className="btn" onClick={greeting()}>Greet</button>
</div>
)
我收到一条错误消息:“无法读取未定义的属性'firstName'”,并且如果我仅在方法中使用“ firstName”和“ lastName”而不使用“ this”关键字的话,也会得到[object object]。如何访问变量?
翻过高山走不出你
墨色风雨
相关分类