Search code examples
react-nativeviewprop

accessing props using ref call back


I am scratching my head hard; trying to figure out what's wrong in below snippet.

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>
    )
  }
}

basically trying to get the props from <View> element i.e. this._root.props using ref callback

though this._root1.props works perfectly fine all the times. could someone help me figure out what's the problem with it?

EDIT: I am even able to see this._root but even not this._root.props.me.


Solution

  • Could you try not to do

    alert(JSON.stringify(this._root.props))

    instead just do

    alert(this._root.props)

    i.e. remove JSON.stringify

    The reason it's not working is because View is having a child element with-in itself while with using Text it's not having any child in it.