react-native - 使用 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。
解决方案
你能不能试着不做
警报(JSON.stringify(this._root.props))
而是做
警报(this._root.props)
即删除 JSON.stringify
它不起作用的原因是因为View本身有一个子元素,而使用Text它没有任何子元素。
推荐阅读
- c++ - gRPC async_client 中的内存泄漏
- javascript - 导航到第三方 URL 而不使其在位置值中可用
- javascript - 如何在 React 中自动发出 API 请求?
- c - 在 CTRL-C 处理中删除 ^C
- python - 适合我的简单入门模型的问题
- api - IRI 作为过滤资源的参数
- cron - .net Core HangFire 设置 Cron 时间
- unity3d - unity 错误:UnityLinker.exe 没有正常运行
- azure - Docker 镜像迁移方法(来自 azure registry 的 Nexus)
- r - R 和 XML:“下标越界”错误