反应:点击按钮不起作用
问题描述:
在过去的一个小时里,我一直在试图让这个工作。 onClick任何按钮都不起作用...我做错了什么?反应:点击按钮不起作用
const React = require('react');
class Questionnaire extends React.Component {
constructor (props) {
super(props);
this.state = { selectedSection: 0 };
}
selectSection (e) {
console.log(e);
}
render() {
return (
<div>
<div className='btn-group mr-2' role='group'>
<button className='btn btn-primary' onClick={this.selectSection}>A</button>
<button className='btn btn-secondary' onClick={this.selectSection}>B</button>
<button className='btn btn-secondary' onClick={this.selectSection}>C</button>
<button className='btn btn-secondary' onClick={this.selectSection}>D</button>
</div>
</div>
);
}
}
module.exports = Questionnaire;
我要指出,我使用它明确反应的-意见
答
尝试这个
const React = require('react');
class Questionnaire extends React.Component {
constructor (props) {
super(props);
this.state = { selectedSection: 0 };
}
selectSection = function(e){
console.log(e);
}
render() {
return (
<div>
<div className='btn-group mr-2' role='group'>
<button className='btn btn-primary' onClick={this.selectSection}>A</button>
<button className='btn btn-secondary' onClick={this.selectSection}>B</button>
<button className='btn btn-secondary' onClick={this.selectSection}>C</button>
<button className='btn btn-secondary' onClick={this.selectSection}>D</button>
</div>
</div>
);
}
}
+0
有什么不同? – Navarjun
答
您需要的功能绑定到组件,如下所示:
class Questionnaire extends React.Component {
constructor (props) {
super(props);
this.state = { selectedSection: 0 };
this.selectSection = this.selectSection.bind(this)
}
保持一切相同
答
您需要绑定的方法班上。将此行添加到构造函数中:
this.selectSection = this.selectSection.bind(this);
是否有任何控制台错误? –
没有控制台错误 – Navarjun
代码似乎对我来说工作正常。什么都没有出现在你的尽头? – Iruss