【发布时间】:2019-07-10 16:49:41
【问题描述】:
这是我的第一个 React 应用程序(react@16.8.1 )。我试图找出为什么 onClick 事件在使用基于功能的组件和基于类的组件时处理方式不同。
据我所知,我应该使用基于类的 c。只有当我需要改变它的状态时,对吗?
基于函数的组件抛出 _this is undefined error 但基于类 - 不是。
我在这两种情况下都使用箭头函数而不是绑定函数。
基于功能:
import React from 'react';
const AnswersDisplay = (props) => {
// even with bind I still get "_this is undefined"
//this.onAnswer = this.onAnswer.bind(this);
const answerList = props.answerList.map( (option) => {
return (
<button
onClick={this.onAnswer}
value={option}
className="ui basic green button">{option}
</button>
)
});
const onAnswer = (e) =>{
console.log(e.target.value);
}
return(
<div className="ui two buttons hSpace">{this.answerList}</div>
);
};
export default AnswersDisplay;
vs 基于类的方法。
import React from 'react';
class AnswersDisplay extends React.Component {
constructor(props) {
super(props);
//this.onAnswer = this.onAnswer.bind(this);
}
answerList = this.props.answerList.map( (option) => {
return (
<button
onClick={this.onAnswer}
value={option}
className="ui basic green button">{option}
</button>
)
});
onAnswer = (e) =>{
console.log(e.target.value);
}
render() {
return(
<div className="ui two buttons hSpace">{this.answerList}</div>
);
}
};
export default AnswersDisplay;
【问题讨论】:
-
this在函数组件和类组件中的工作方式不同,因此函数的行为也不同。检查 babel 是如何编译它们的 -
this在函数组件中并不像在类组件中那样引用组件实例。请改用onClick={onAnswer}。 -
而不是
onClick={this.onAnswer}使用onClick={onAnswer} -
谢谢大家的解释!
-
@ElenaJdanova 对答案的支持会有所帮助
标签: javascript reactjs event-handling components