【问题标题】:Cannot call parent component from child component无法从子组件调用父组件
【发布时间】:2018-04-25 21:34:31
【问题描述】:

当我从 Text 组件中删除动画类时,这段代码 sn-p 运行良好。但是我不明白为什么在尝试将子组件与动画 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>
    );
  }
}

【问题讨论】:

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


    【解决方案1】:

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

    childButton = () => {
      this.props.callback(this.props.id);
    }
    

    【讨论】:

    • 嗯,我很确定它正在做同样的事情,即绑定类上下文。看看那个medium.com/@charpeni/…
    • 如果您关心转译/可测试性,那么我建议直接将值传递给childButton,而不是通过props 访问它
    • 其实我是,但对于我自己的项目,动画中的数据流非常复杂。我仍在努力,但作为一个问题发布,我刚刚提取了我遇到问题的代码。
    猜你喜欢
    • 1970-01-01
    • 2020-02-15
    • 2021-05-02
    • 1970-01-01
    • 2022-07-07
    • 2023-01-08
    • 2018-07-16
    • 2018-06-08
    相关资源
    最近更新 更多