【问题标题】:OnClick Not Working While Looping To Other Components in React在 React 中循环到其他组件时 OnClick 不工作
【发布时间】:2018-03-04 16:04:20
【问题描述】:

对不起,函数名称

我有一个基本的反应应用程序,它可以获取数据,即博客的标题和主题并显示在网站上

这是我的列表组件

import React , {Component} from 'react';

import axios from 'axios'
import Card from './Card.js'

var cardComponent;
class getBlogs extends Component {
  componentDidMount(){
    axios.get('http://localhost:8081/v1/todolist/todo1', {})
      .then( (response)=> {
        this.setState({retrieved : true})
        this.setState({data : response.data})
      })
      .catch(function (error) {
        console.log(error);
      });   
  }

  constructor(){
    super();
    this.state = {
      data : 'none' ,
      retrieved : 'true'
    }
  }

  onned = (event)=>{
    console.log('lof')
  }

  oh = ()=>{
    if(this.state.data !== 'none'){
       cardComponent = this.state.data.map((user , i)=>{
        var some = this.state.data;
        console.log(some[i].title)
        return <Card
          onClick={this.onned()}
          title={some[i].title}
          topic={some[i].topic}
        /> ;
      });
      return cardComponent;
    }
 }

 render(){
    if(this.state.retrieved === true){
      return (
        <div>{this.oh()}</div>
      );
    }
    else{
      return (
          <h1>Loading............................</h1>
      );
    }
  }
}

export default getBlogs;

它正在获取数据,oh函数循环数据并发送到卡组件

卡片.js

import React from 'react';

class Card extends React.Component {
  constructor(props) {
    super(props);
  }

  onDiv = (event)=>{
    console.log('hello')
  }

  render() {
    return (
      <div className="container">
          <div  onClick ={this.onDiv()} style={{backgroundSize : 'cover'}} className=" form-control bg-light-green dib br3 pa3 ma2 grow bw2 shadow-5">
              <div style={{marginLeft : '90px'}}>
                   <h1   style={{ textAlign : "center" , color : "red" , fontWeight : "bold"}} className="display-2">{this.props.title}</h1>
                   <h1   style={{ textAlign : "center" , color : "blue" , fontWeight : "bold"}} className="">{this.props.topic}</h1>
             </div>
          </div>
          <br/>
          <br/>
       </div>
    );
  }
}

export default Card;

现在我想要的是,如果用户单击博客名称列表之一,它应该重定向到其他位置,但 div 的 onClick 不起作用

在渲染自身时,onClick 被执行

请不要投反对票,我可能会被阻止

【问题讨论】:

  • 试试onClick ={() =&gt; this.onDiv()}
  • 您正在立即调用函数onDiv。不要给自己打电话,让它被onClick事件调用,比如onClick ={this.onDiv}
  • 非常感谢。非常 。我做错的事情是把那些括号。你能简单解释一下为什么会这样吗
  • 当你喜欢onClick={this.onDiv}下面的评论时,你通过引用将函数onDiv绑定到onClick,所以如果onClick有对函数的引用,它可以执行它。但是当你像{this.onDiv()}一样传递它时,你立即执行函数onDiv并将函数的结果传递给onClick,当然你不能将它作为函数执行。
  • 请大家帮忙

标签: javascript reactjs web frontend react-component


【解决方案1】:

使用此onClick ={this.onDiv} 而不是onClick ={this.onDiv()}。而不是为 onClick 提供回调,您只调用那里的函数

【讨论】:

猜你喜欢
  • 2018-05-17
  • 1970-01-01
  • 2023-04-09
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多