【发布时间】:2017-07-25 20:09:27
【问题描述】:
即使在 SO 上的其他问题中找到建议后,我似乎仍然无法让 onClick 函数 this.changeContent 正常工作:
import React from 'react';
import Maxim from './Maxim';
import Challenge from './Challenge';
import Prompt from './Prompt';
class ContentContainer extends React.Component {
constructor() {
super();
this.changeContent = this.changeContent.bind(this);
this.state = {
content: "maxim"
}
}
changeContent(event) {
console.log(this);
if (this.state.content == "maxim") {
this.setState({ content: "challenge" })
} else {
this.setState({ content: "maxim" })
}
}
render() {
let renderedContent = null;
if (this.state.content == "challenge") {
renderedContent = <Challenge content="The trick to presence is to listen to the space between the sounds." />;
} else {
renderedContent = <Maxim quote="Silence can be heard in every sound. All you need is to listen." />;
}
return (
<div className="content-container">
{renderedContent}
<Prompt onClick={this.changeContent}/>
</div>
);
}
}
export default ContentContainer;
我尝试过使用bind、箭头函数(如这里)、普通函数参考...几乎所有我在 SO 和其他地方看到的变体。我最初只有this.changeContent(),并且在页面加载时调用了该函数。我至少已经解决了这个问题,但这个函数仍然没有被调用——this.state.content 没有改变,控制台日志this 也没有。
谢谢。
【问题讨论】:
-
您发布的代码看起来不错。如果它不起作用,那么问题可能出在其他地方。请发布所有相关信息。
-
是的,如下所述,是
<Prompt/>本身缺少导致问题的函数引用。
标签: javascript reactjs onclick ecmascript-6 arrow-functions