簡體   English   中英

無法從子組件調用父組件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM