无法访问 refs 以从不同的组件调用方法

Can't access refs to call a method from a different component

我是 React-Native 的新手,我一直在尝试从另一个组件调用方法,但我似乎无法正确访问引用。这是我的渲染方法的样子

<Content contentContainerStyle={styles.content}>
...
  <PostComponent style={styles.cardStyle} ref="cardRef" />
     <View style={styles.horizontalTextContainer}>
       <this.refs.cardRef.getText />
     </View>
...
</Content>

在 PostComponent 组件中,这是我尝试调用的方法:

  getText() {
    return (
      <Text>Hello</Text>
    );
  }

在同一个组件的构造函数中,我可以使用 refs 来调用这样的方法:

constructor(props) {
    super(props);
    newthis = this
    this.state = {
      time: 20,
      cards: [],
    }
    var timer = setInterval(() => {
      this.setState({
      time: --this.state.time,
     })
     if(this.state.time == 0) {
        this.setState({
          time: 20,
        })
        this.refs.cardRef.timesUp();
      }
    }, 1000);
  }

奇怪的是,ref 在 setInverval 方法内部工作,但不在方法外部 - 作用域在这里如何工作?此外,如果您注意到我有一个 hacky "newthis" 来保存全局 this - 因为在组件的某些方法中我无法访问 "this"(未定义)。

在构造函数中,调用时组件还没有挂载。只有在 componentDidMount 生命周期方法之后才能安全访问 refs。字符串类型的引用也被弃用 https://facebook.github.io/react/docs/refs-and-the-dom.html 。请使用回调函数语法。

在您的情况下,由于时间间隔,refs 可能在 setInterval 中工作。该组件将由 1000 毫秒安装。

并且为了避免 hacky newThis,您可以使用箭头函数或在构造函数中绑定它。大多数组件的回调函数都有自己的 this 上下文。

constructor(props) {
    super(props);
    newthis = this
    this.state = {
      time: 20,
      cards: [],
    }
 }
 componentDidMount() {
  this.timer = setInterval(() => {
      this.setState({
      time: --this.state.time,
     })
     if(this.state.time == 0) {
        this.setState({
          time: 20,
        })
        this.cardRef.timesUp();
      }
    }, 1000);
  }
  componentWillUnmount() {
   clearInterval(this.timer)
  }
...

<Content contentContainerStyle={styles.content}>
...
  <PostComponent style={styles.cardStyle} ref={(ref) => this.cardRef = ref} />
     <View style={styles.horizontalTextContainer}>
       {this.cardRef.getText()}
     </View>
...
</Content>