繁体   English   中英

使用ref回调访问道具

[英]accessing props using ref call back

我用力地挠头。 试图找出下面的代码段出了什么问题。

import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';

class MyButton extends React.Component {

  setNativeProps = (nativeProps) => {
    alert(JSON.stringify(this._root.props)) //able to get this.v here
  }

  render() {
    return (
      <View ref={cc => {this._root = cc; this.v = 100 }} me="tom">
        <Text ref={component => { this._root1 = component;}} style={{margin:55}} onPress={()=>this.setNativeProps({text:'fgfg'})}>{this.props.label} </Text>
      </View>
    )
  }
}

export default class App extends React.Component {
  render() {
    return (
      <TouchableOpacity >
        <MyButton label="Press me!" />
      </TouchableOpacity>
    )
  }
}

基本上试图使用ref回调<View>元素(即this._root.props获取道具

尽管this._root1.props正常工作。 有人可以帮我找出问题所在吗?

编辑:我什至能够看到this._root但甚至看不到this._root.props.me。

你能试着不做吗

警报(JSON.stringify(this._root.props))

而是做

警报(this._root.props)

即删除JSON.stringify

它不起作用的原因是因为View本身具有子元素,而使用Text时却没有任何子元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM