我正在尝试渲染从父组件传递的特定位置的地图。我正在使用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;
目前,编译时出现问题,因为渲染时bar
未定义。有什么建议/意见吗?
答案 0 :(得分:5)
首先,在React组件中,render()
方法是虚拟DOM(由React保存在内存中)与显示给用户的具体DOM之间的桥梁。我已经阅读了有关React component's lifecycle的更多信息 - 理解这是理解的反应。
此外,为了在页面中显示您的GoogleMapContainer
,您需要在React renderMap()
方法中调用方法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>
)
}
}
}