对于某些重复的问题感到抱歉,但我在其他帖子上看到的有效答案与我尝试过的完全匹配,我有点迷失了。我只是想让我的按钮触发onClick事件。它不会触发,我的handleClickNewQuote方法中的代码为零。
我相信你可以告诉我,对于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 :(得分:0)
这是因为在onClick
中的箭头函数中,您没有返回要运行的handleClickNewQuote()
函数。
因此,如果您执行以下操作,则会触发:
onClick={() => this.handleClickNewQuote}
然而,为了进一步简化这一点,我们可以完全删除包装函数:
onClick={this.handleClickNewQuote}