[英]Cannot call parent component from child component
This code snippet works pretty well when I remove animated class from Text component. 当我从Text组件中删除动画类时,此代码段效果很好。 However I couldn't figure it out why I couldn't call parent components' function from child component while I'm trying to use child component with animated api. 但是我无法弄清楚为什么我试图通过动画api使用子组件时不能从子组件调用父组件的功能。
import React from 'react';
import { Animated, TouchableOpacity, StyleSheet, Text, View, Dimensions } from 'react-native';
class Txt extends React.Component {
constructor() {
super()
this.childButton = this.childButton.bind(this);
}
componentWillMount() {
this.position = new Animated.ValueXY({ x: 200, y: 400 });
}
childButton() {
this.props.callback(this.props.id);
}
render() {
return (
<TouchableOpacity onPress={this.childButton}>
<Animated.Text style={{ transform: [{ translateY: this.position.y }] }}>
button
</ Animated.Text >
</TouchableOpacity >
)
}
}
export default class App extends React.Component {
constructor() {
super()
this.parentButton = this.parentButton.bind(this);
}
parentButton(param) {
console.log(param);
}
render() {
return (
<View>
<Txt callback={this.parentButton} id="_3131" />
</View>
);
}
}
use arrow functions for your declarations in place of bind
. 在声明中使用箭头函数代替bind
。 In this case you are trying to access this.props.callback
in childButton
which is a closure scope that does not have a props
property. 在这种情况下,您尝试访问this.props.callback
中的childButton
,这是一个没有props
属性的闭包范围。
childButton = () => {
this.props.callback(this.props.id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.