使用 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>
)
}
}
基本上是尝试从 <View>
元素获取道具,即 this._root.props
使用 ref 回调
虽然 this._root1.props
一直工作得很好。
有人可以帮我弄清楚它有什么问题吗?
编辑:
我什至可以看到 this._root
但甚至看不到 this._root.props.me.
能不能尽量不做
alert(JSON.stringify(this._root.props))
而只是
alert(this._root.props)
即删除 JSON.stringify
它不起作用的原因是因为 View 在使用 Text[=24 时有一个 child 元素 with-in 本身=] 它里面没有任何 child。
我正在苦苦思索;试图找出下面代码段中的错误。
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.
能不能尽量不做
alert(JSON.stringify(this._root.props))
而只是
alert(this._root.props)
即删除 JSON.stringify
它不起作用的原因是因为 View 在使用 Text[=24 时有一个 child 元素 with-in 本身=] 它里面没有任何 child。