Reactjs 在子组件中获取道具以供内部函数使用
我得到了一个组件Reactjs 在子组件中获取道具以供内部函数使用,reactjs,Reactjs,我得到了一个组件a: import React, { Component } from 'react' import Gmap from '../global/gmap.component' class RandomPlace extends Component { render() { return ( <Gmap address={this.state.random.location} /> 这个{This.props.address}在我点击组件a上
a
:
import React, { Component } from 'react'
import Gmap from '../global/gmap.component'
class RandomPlace extends Component {
render() {
return (
<Gmap address={this.state.random.location} />
这个{This.props.address}
在我点击组件a
上的“重新加载”按钮时会很好地显示和更新。此时,React Chrome扩展很好地显示了道具的地址内容。并且看到它在“重新加载”操作中得到了很好的更新
问题是,在我的组件Gmap
的内部函数中,我似乎无法访问props属性address
,比如componentDidMount()
或aCustomFunction()
我已经对此进行了测试:
componentDidMount () {
console.log('gmap did mount')
this.setState({address: this.props.address})
let x = this.props.address
let y = this.state.address
console.log(x)
console.log(y)
在类的顶部有一个构造函数:
constructor (props) {
super(props)
this.state = {
address: 'xx'
}
但是什么也没有出现。我是一个新的反应,我肯定我错过了一些基本的东西,但看不见它。
提前感谢。您是否在询问如何在子组件上调用自定义函数?如果是,
<Gmap address={this.state.random.location} ref={(map) => { this.map = map; }} />
我不完全确定,但我认为会是这样:
address={this.state.random.location}
从状态中设置,如您所见constructor(){
super();
this.state={
random: {location: "some test value"}
}
}
您将在控制台日志中看到“一些测试值”,而不是未定义的。您在日志中看到了什么?我得到了
未定义的和xx
。最好在返回jsx之前检查渲染中的道具和状态,react-chrome开发工具对调试此类情况有很大帮助。是的,我尝试使用react-chrome dv工具,这一切看起来都很好,更新也很好。我试了一下,日志看起来是正确的,不是吗?不,我想知道如何在child(Gmap)元素的函数中使用通过prop传递的位置。尽管显示本身可以在渲染中工作。
this.map.aCustomFunction()
constructor(){
super();
this.state={
random: {location: "some test value"}
}
}