在React中循环使用其他组件时OnClick不工作

问题描述 投票:0回答:1

对不起功能名称

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

这是我的列表组件

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;

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

Card.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;

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

在渲染自身时onClick得到执行

请不要downvote我可能会被阻止

javascript reactjs web frontend react-component
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.