无法从子组件调用父组件

时间:2018-04-25 21:34:31

标签: javascript reactjs animation react-native ecmascript-6

当我从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>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

使用箭头函数代替bind进行声明。 在这种情况下,您尝试访问this.props.callback中的childButton,这是一个没有props属性的闭包范围。

childButton = () => {
  this.props.callback(this.props.id);
}
相关问题