【问题标题】:react native: attempted to assign to readonly property反应原生:试图分配给只读属性
【发布时间】:2019-03-20 03:10:34
【问题描述】:

我通过在 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>
    )
  }
}

但是当我使用回调方式分配react ref时,一切正常。

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

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

【问题讨论】:

  • 查看这篇我发现的关于可能有帮助的主题的文章:medium.com/@martin_hotell/… 此外,将 typescript 标签添加到您的问题中可能会有所帮助

标签: reactjs typescript react-native


【解决方案1】:

React 中的 ref 属性需要一个函数,并且在组件安装后立即调用它。除了设置参考之外,您还可以做其他事情。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2016-07-19
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    相关资源
    最近更新 更多