[英]Cannot call parent component from child component
当我从Text组件中删除动画类时,此代码段效果很好。 但是我无法弄清楚为什么我试图通过动画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>
);
}
}
在声明中使用箭头函数代替bind
。 在这种情况下,您尝试访问this.props.callback
中的childButton
,这是一个没有props
属性的闭包范围。
childButton = () => {
this.props.callback(this.props.id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.