2017-08-14 115 views
-1

在过去的一个小时里,我一直在试图让这个工作。 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; 

我要指出,我使用它明确反应的-意见

+1

是否有任何控制台错误? –

+0

没有控制台错误 – Navarjun

+1

代码似乎对我来说工作正常。什么都没有出现在你的尽头? – Iruss

回答

-1

我相信参数的onClick应该是进行评估,以评估的表现,而不是一个表达式,然后将结果执行。换句话说,我认为代码应该是:

<button className='btn btn-secondary' onClick={this.selectSection()}>D</button> 

与parens。

+0

仍然没有工作... :( – Navarjun

+0

)你是否投我票,因为我的建议没有工作?无论如何,看看点击是否工作:'' – Malvolio

+0

因为它不正确,我就低估了它的效率,onClick会像在JS中一样收到一个回调,这在Angular中是正确的,而不是React –

0

尝试这个

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

0

您需要的功能绑定到组件,如下所示:

class Questionnaire extends React.Component { 
    constructor (props) { 
     super(props); 
     this.state = { selectedSection: 0 }; 

     this.selectSection = this.selectSection.bind(this) 
    } 

保持一切相同

0

您需要绑定的方法班上。将此行添加到构造函数中:

this.selectSection = this.selectSection.bind(this);