如何使用React渲染组件onClick?
问题描述:
我试图呈现从父组件传递的特定位置的映射。我正在使用谷歌地图反应,我不确定的两件事:如何使用React渲染组件onClick?
如何调用函数onClick
在我的渲染。以及如何在我的类中编写呈现我想要的组件的函数。这是世界卫生大会TI迄今为止:
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
渲染时是不确定的。任何建议/建议?
答
首先,在React组件中,render()
方法是虚拟DOM(由React保存在内存中)和具体DOM显示给用户的桥梁。我读了更多关于React component's lifecycle - 理解这是理解反应。
此外,为了在页面中显示您的GoogleMapContainer
,您需要在React render()
方法中调用您的方法renderMap()
,将结果存储在变量中并将其返回。
要完全可能调用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>
)
}
}
}
+0
这真的很有帮助,非常感谢。 – user7496931
你们是不是有选择地呈现地图如果this.props.selectedBar定义? – Matthew
首先,你的'renderMap()'应该返回Jsx –
而你并没有在那里使用 –