如何使用React渲染组件onClick?

6 jsx npm reactjs google-maps-react

我正在尝试渲染从父组件传递的特定位置的映射.我正在使用google-maps-react,我不确定两件事:

如何onClick在渲染中调用函数.以及如何在我的类中编写函数来呈现我想要的组件.到目前为止这是:

import React, { Component } from 'react';
import yelp from 'yelp-fusion';
import xhr from 'xhr';
import GoogleMapContainer from './Map';

class BusinessCard extends Component {
  constructor () {
    super()

    this.renderMap = this.renderMap.bind(this);
  }

  renderMap(){
    <GoogleMapContainer barLat={bar.coordinates.latitude} barLong={bar.coordinates.longitude} />
  }

  render() {
    const newCard = this.props.newCard
    const bar = this.props.selectedBar
    // console.log("this are the coordinates", bar["coordinates"])
    if(bar.coordinates){
      return (
        <div>
          <p>{bar.coordinates.longitude}</p>
          <p>{bar.name}</p>
          <img src={bar.image_url} />
          <button> X </button>
          <button onClick={newCard}> Yes </button>

        </div>
      )
    } else {
      return(
        <div>Loading...</div>
      )
    }
  }
}

export default BusinessCard;
Run Code Online (Sandbox Code Playgroud)

目前,编译bar时存在问题,因为渲染时未定义.有什么建议/意见吗?

Dra*_*scu 5

首先,在React组件中,render()方法是您在虚拟DOM(由React保留在内存中)和向用户显示的具体DOM之间的桥梁。我已经阅读了更多有关React 组件生命周期的信息 -了解这就是理解React 。

此外,为了GoogleMapContainer在页面中显示您,您需要renderMap()在React render()方法中调用您的方法,将结果存储在变量中并返回。

onClick完全调用多个函数,可以将一个函数传递给处理程序,然后在其中调用所需的函数数量。

检查以下示例:

import React, { Component } from 'react';
import yelp from 'yelp-fusion';
import xhr from 'xhr';
import GoogleMapContainer from './Map';

class BusinessCard extends Component {
  constructor () {
    super()

    // LOOK MORE WHAT 'this' means!! <- the key of javascript = execution context
    this.renderMap = this.renderMap.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  renderMap(){
    // carefull!!! bar is undefined. Look more what 'this' means in javascript
    const bar = this.props.selectedBar;
    return (
      <GoogleMapContainer barLat={bar.coordinates.latitude} barLong={bar.coordinates.longitude} />
    );
  }

  handleClick() {
    const newCard = this.props.newCard;

    // call the newCard function prop (if only is a function!!!)
    newCard();

    // another method call
    this.anotherMethod();
  }

  anotherMethod() {
    console.log('heyo!');
  }

  render() {
    const newCard = this.props.newCard
    const bar = this.props.selectedBar
    // console.log("this are the coordinates", bar["coordinates"])
    if(bar.coordinates){
      const renderMap = this.renderMap();
      return (
        <div>
          <p>{bar.coordinates.longitude}</p>
          <p>{bar.name}</p>
          <img src={bar.image_url} />
          <button> X </button>
          <button onClick={this.handleClick}> Yes </button>
          { renderMap }
        </div>
      )
    } else {
      return(
        <div>Loading...</div>
      )
    }
  }
}
Run Code Online (Sandbox Code Playgroud)