React-Native:createRefCan无法添加属性值,对象不可扩展

时间:2019-03-19 12:27:45

标签: typescript react-native

我刚刚开始使用React-Native和TypeScript:

export default class List extends PureComponent<Props, object> {
   private flatListRef: React.RefObject<FlatList<any>>;

  constructor(props) {
    super(props);
    this.flatListRef = React.createRef<FlatList<any>>();
  }
  
  render() {
    const { data = [1, 2, 3, 4, 5] } = this.props;
    return (
      <View
        style={{
          paddingBottom: 60,
          height: "100%",
        }}
      >
        <FlatList
          ref={this.flatListRef}
          data={data}
          ListHeaderComponent={
            <Image
              style={styles.headImg as ImageStyle}
              source={{ uri: ''}}
              resizeMode="contain"
            />
          }
          renderItem={this._renderItem}
          keyExtractor={(item, index) => {
            return `${item.id + index + 2}`
          }}
          stickyHeaderIndices={[1]}
        >
        </FlatList>

      </View>
      );
   }
}

我遇到了一个错误:

enter image description here

但是当我使用Callback Refs时,没有错误。

我不知道为什么React.createRef不起作用。

2 个答案:

答案 0 :(得分:0)

您可以通过在componentWillMount中重新分配该对象来取消冻结该对象:

componentWillMount() {
    this.refs = {}
}

答案 1 :(得分:0)

尝试像这样修改您的代码。

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

  constructor(props) {
    super(props);
    this.flatListRef = React.createRef(); // modified
  }

我没有错误