即使遵循了在其他问题中找到的建议后,我似乎仍然无法让 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
.
谢谢。
最佳答案
检查这个工作示例,以类似的方式编写它:
class ContentContainer extends React.Component {
constructor() {
super();
this.changeContent = this.changeContent.bind(this);
this.state = {
content: "maxim"
}
}
changeContent(event) {
let content = this.state.content;
this.setState({ content: content == "challenge" ? "maxim" : "challenge"})
}
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>
);
}
}
class Challenge extends React.Component{
render(){
return(
<div>Inside Challenge<br/>{this.props.content}</div>
)
}
}
class Maxim extends React.Component{
render(){
return(
<div>Inside Maxim<br/>{this.props.quote}</div>
)
}
}
class Prompt extends React.Component{
render(){
return(
<div style={{paddingTop: '100px'}}>
Inside Prompt<br/>
<span onClick={()=>this.props.onClick()}>*Click Me to change the Component</span>
</div>
)
}
}
ReactDOM.render(<ContentContainer/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
关于javascript - 如何让 React onClick 工作? (即使使用箭头功能也不起作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42617443/