简体   繁体   English

在 React Native 的 FlatList 中使用 ref

[英]Using a ref in a FlatList in React Native

I am still having trouble understanding ref's in React Native (and React in general).我仍然无法理解 React Native(以及一般的 React)中的 ref。 I am using functional component.我正在使用功能组件。 I have a FlatList that has many items.我有一个包含许多项目的 FlatList。 How do I create a reference for a thing within an item like a Text or View component?如何为文本或视图组件等项目中的事物创建引用?

<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>
 }
/>

Then in _editItem I want to reference the Text component so that I can change its text from 'EDIT' to 'EDITING', or even change its style, or whatever.然后在_editItem中,我想引用 Text 组件,以便可以将其文本从“EDIT”更改为“EDITING”,甚至更改其样式或其他任何内容。

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

I have tried...我努力了...

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>
 }
/>

...and a few other things, but I think I might be way off so I could use some guidance. ...以及其他一些事情,但我想我可能会走得很远,所以我可以使用一些指导。

Typically you don't use refs in react to update content like text.通常,您不会在响应中使用 refs 来更新文本等内容。 Content should be rendered based on the current props and state of your component.内容应基于组件的当前道具和 state 呈现。

In the case you describe you'll probably want to set some state in the parent component that then impacts the rendering of the item.在您描述的情况下,您可能希望在父组件中设置一些 state ,然后影响项目的呈现。

As a sidenote refs are used if you need to trigger a method on a child component like calling focus on a TextInput for example but not for imperatively updating component content.作为旁注,如果您需要在子组件上触发方法,例如在TextInput上调用focus ,但不用于强制更新组件内容,则使用参考文献。

In your case you'll want to update some state representing the current active item.在您的情况下,您需要更新一些代表当前活动项目的 state。 Something like:就像是:

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}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM