在React Native的FlatList中使用ref

时间:2019-09-25 06:57:51

标签: javascript react-native react-native-flatlist ref

我仍然在理解React Native(和一般的React)中的ref时遇到麻烦。我正在使用功能组件。我有一个包含很多项目的FlatList。如何为诸如Text或View组件之类的项目中的事物创建引用?

<FlatList
 data={data}
 renderItem={({ item }} => {
   <View>

    ... lots of other stuff here

    <TouchableOpacity onPress={() => _editITem(item.id)}>
      <Text ref={(a) => 'text' + item.id = a}>EDIT</Text>
    </TouchableOpacity>

  </View>
 }
/>

然后在_editItem中,我想引用Text组件,以便可以将其文本从“ EDIT”更改为“ EDITING”,甚至可以更改其样式,或其他。

_editPost = id => {
  console.log(text + id)
}

我尝试过...

FeedComponent = () => {
  let editPosts = {}

 <FlatList
 data={data}
 renderItem={({ item }} => {
   <View>

    ... lots of other stuff here

    <TouchableOpacity onPress={() => _editITem(item.id)}>
      <Text ref={(a) => editPosts[item.id] = a}>EDIT</Text>
    </TouchableOpacity>

  </View>
 }
/>

...还有其他一些事情,但是我想我可能还差得远,所以我可以使用一些指导。

1 个答案:

答案 0 :(得分:1)

通常,您不使用ref来更新文本之类的内容。内容应根据组件的当前属性和状态进行呈现。

在您描述的情况下,您可能需要在父组件中设置一些状态,然后影响项目的呈现。

作为旁注,如果您需要在子组件上触发方法,例如在focus上调用TextInput,而不是强制更新组件内容,则使用refs。

在您的情况下,您需要更新一些表示当前活动项目的状态。像这样:

import React, {useState} from 'react';
FeedComponent = () => {
  const [activeItem, setActiveItem] = useState(null);

 <FlatList
 data={data}
 renderItem={({ item }} => {
   return (
   <View>

    ... lots of other stuff here

    <TouchableOpacity onPress={() => setActiveItem(item.id)}>
      {activeItem === item.id
          ? <Text>EDITING</Text>
          : <Text>EDIT</Text>
      }
    </TouchableOpacity>

  </View>
 );
 }
 extraData={activeItem}
/>