【发布时间】:2019-06-18 20:51:56
【问题描述】:
我的 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
【问题讨论】:
-
这是一个工作沙箱:codesandbox.io/s/r4zrkqpyy4 当我单击按钮时,控制台消息会被记录下来。除了删除您未包含在沙箱中的文件的导入和代码引用之外,我没有进行任何更改。
标签: javascript reactjs button