2017-10-21 583 views
0

對不起有些重複的問題,但我在其他帖子上看到的有效答案完全匹配我所嘗試的內容,並且我有點迷路。我只是試圖讓我的按鈕的onClick事件觸發。它不會觸發,我的handleClickNewQuote方法中的代碼執行零。onClick事件不會觸發

我確定你可以告訴我對React非常新,如果你願意的話,這只是我的應用程序的粗略草稿。

import React, { Component } from 'react'; 
import './App.css'; 
import axios from 'axios'; 




class App extends Component { 
    constructor(props){ 
    super(props) 
    this.state={ 
     quote: this.quote, 
     author: this.author, 
     category: this.category 
    } 
    this.handleClickNewQuote = this.handleClickNewQuote.bind(this); 
    // this.handleClickTweet = this.handleClickTweet.bind(this); 
    // this.handleClickSave = this.handleClickSave.bind(this); 
    } 

    //Fires when app is loaded~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

    componentDidMount(){ 
    axios.get('http://localhost:3001/api/getQuote').then(response =>{ 
     this.setState({quote: response.data.quote, 
        author: response.data.author, 
        category: response.data.category}) 
    }).catch(console.log) 
    } 

    //Fires when NewQuote is clicked, makes API call to server and gets data back 

    handleClickNewQuote(){ 
    axios.get('http://localhost:3001/api/getQuote').then(response =>{ 
     this.setState({quote: response.data.quote, 
        author: response.data.author, 
        category: response.data.category}) 
    }).catch(console.log) 
    console.log("Button is working?"); 
    } 


    render() { 
    return (
     <div className="App"> 
     <div id="main-container"> 
      <div id="quote-box"> 
      <p id="quote-text">{this.state.quote}</p> 
      <div id="author-name"> 
      <p id="author-text">{this.state.author}</p> 
       <div id="button-box"> 
       <button type="button" className="button-color" id="save-button">Save</button> 
       <button type="button" className="button-color" id="tweet-button">Tweet</button> 
       <button type="button" className="button-color" id="new-quote-button" onClick={() => {this.handleClickNewQuote}}>New Quote</button> 
       </div> 
      </div> 
      </div> 
     </div> 
     </div> 
    ); 
    } 
} 

export default App; 
+0

火一個函數,你需要把'()'放在最後。 'onClick = {()=> {this.handleClickNewQuote}}'onClick = {()=> {this.handleClickNewQuote()}}'' – bennygenel

回答

0

這是因爲在onClick您的箭頭功能,您不必返回handleClickNewQuote()功能跑出。

所以,如果你做了以下將火:

onClick={() => this.handleClickNewQuote}

然而,爲了簡化這個更我們只能完全刪除的包裝功能部件:

onClick={this.handleClickNewQuote}