reactjs – 如何使用React渲染组件onClick?
发布时间:2020-12-15 05:04:07 所属栏目:百科 来源:网络整理
导读:我正在尝试渲染从父组件传递的特定位置的映射.我正在使用google-maps-react,我不确定两件事: 如何在我的渲染中使用onClick调用函数.以及如何在我的类中编写函数来呈现我想要的组件.到目前为止这是: import React,{ Component } from 'react';import yelp f
我正在尝试渲染从父组件传递的特定位置的映射.我正在使用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.有什么建议/意见吗?
首先,在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> ) } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |