2017-08-14 173 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);