首页 > 解决方案 > 反应原生:试图分配给只读属性

问题描述

我通过在 React Native 中调用 React.createRef 创建一个 React ref。然后我将它分配给一个参考。我收到错误:尝试分配给只读属性

export default class List extends PureComponent<Props, object> {

  private flatListRef: React.RefObject<FlatList<any>>;

  constructor(props) {
    super(props);
    this.flatListRef = React.createRef();
  }
  render() {
    return (
      /.../
      <FlatList ref={this.flatListRef}></FlatList>
    )
  }
}

但是当我使用回调方式分配反应参考时,一切正常。

<FlatList ref={ele => { this.flatListRef = ele }}></FlatList>

我不知道这两种方式有什么区别

标签: reactjstypescriptreact-native

解决方案


the ref property in React is expecting a function and it's called immediately after the component is mounted. You can do other things besides setting a reference.

https://zhenyong.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute


推荐阅读