javascript - 反应按钮没有响应点击
问题描述
我的 React 按钮的点击没有响应 onClick。我只是在做一个简单的 console.log(),这甚至都行不通。
奇怪的是,当我也将按钮放在 App.js 中时,该按钮将单击我的其他组件,但不会没有它。这让我觉得它与它的安装方式有关。
在 App.js 中,我在 App.js 的 render() 中有以下内容来路由到我的组件(Tweets.js):
<div className="App-intro">
<Switch>
<Route path="/home" component={Home}/>
<Route path="/appTweets" render={(props) => <Tweets {...props} tweets="home" />} />
</Switch>
这是 Tweets.js:
import React, { Component } from 'react'
import {Tweet} from 'react-twitter-widgets';
const TweetList = (props) => {
console.log('tweet list props');
console.log(props)
return (
<div>{props.tweets.map(tweet=> <Tweet key={tweet.tweet_id} {...tweet}/>)}
</div>
);
}
class Tweets extends React.Component {
constructor(props) {
super(props)
console.log("tweet props");
console.log(props);
this.handleClick=this.handleClick.bind(this);
this.state = {
error: null,
isLoaded: false,
items: [],
tweets: [],
selectedPolitician: null,
}
}
handleClick(e) {
console.log('clicked aoc ');
console.log(e);
}
componentDidMount() {
console.log("fetching the hostname");
// fetch(HOST_NAME + TWEET_ENDPOINT)
var hostname = "";
if (window.location.hostname === "localhost"){
hostname = "http://localhost:8000";
} else {
hostname = "https://pst-360.herokuapp.com"
}
console.log(hostname);
fetch(hostname + "/tweets/?format=json")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result,
tweets: result.results.map(function(tweet){
return {"tweetId": tweet.tweet_id};
})
});
console.log("got result!");
console.log(result);
}
)
}
render() {
return (
<div className="container-fluid text-center">
<button type="button" className="btn btn-primary" onClick={this.handleClick.bind(this)}>Alexandria Ocasio Cortex</button>
<div className="row content">
</div>
<div className="col-sm-8 text-left">
<TweetList tweets={this.state.tweets} />
</div>
<div className="col-sm-2 sidenav">
</div>
</div>
)
}
}
export default Tweets
解决方案
关于onClick,我能看到的唯一问题是您已经在构造函数中为handleClick 进行了绑定,因此在调用按钮onClick 时再次不需要绑定。否则一切看起来都很好按钮应该可以工作请仔细检查
改变
onClick={this.handleClick.bind(this)}
至
onClick={this.handleClick}
推荐阅读
- polymer - WebComponent 和 lit-html 的区别
- sql - 我可以在 SQL 的另一个聚合器中使用聚合器吗?
- flutter - 颤振:未来
返回 null 但如果打印它有值 - java - api 文档 Swagger 中未添加的 ExclusiveMaximum 注释
- mongodb - MongoDB 指南针在“激活插件”屏幕上停止
- python - Get specific value BeautifulSoup (parsing)
- pine-script - Pine Script : 直方图的颜色不能着色
- python-3.x - 使用 python openpyxl 的多列样式
- git - 如何合并已发布的修补程序以开发与拉取请求中的冲突?
- c++ - 如何找出`duration_cast的真实类型
(steady_clock::now().time_since_epoch()).count()`