首页 > 解决方案 > 使用 ref 回调访问道具

问题描述

我正在努力挠头;试图找出下面的代码片段有什么问题。

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

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

虽然this._root1.props一直都很好用。有人可以帮我弄清楚它有什么问题吗?

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

标签: react-nativeviewprop

解决方案


你能不能试着不做

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

而是做

警报(this._root.props)

即删除 JSON.stringify

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


推荐阅读