首页 > 解决方案 > 反应按钮没有响应点击

问题描述

我的 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

标签: javascriptreactjsbutton

解决方案


关于onClick,我能看到的唯一问题是您已经在构造函数中为handleClick 进行了绑定,因此在调用按钮onClick 时再次不需要绑定。否则一切看起来都很好按钮应该可以工作请仔细检查

改变

   onClick={this.handleClick.bind(this)}

   onClick={this.handleClick}

推荐阅读