2017-10-21 232 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}