【问题标题】:Using a ref in a FlatList in React Native在 React Native 的 FlatList 中使用 ref
【发布时间】:2020-01-25 07:28:46
【问题描述】:

我仍然无法理解 React Native(以及一般的 React)中的 ref。我正在使用功能组件。我有一个包含许多项目的 FlatList。如何为文本或视图组件等项目中的事物创建引用?

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

...还有一些其他的事情,但我想我可能还有一段路要走,所以我可以使用一些指导。

【问题讨论】:

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


    【解决方案1】:

    通常您不会在响应中使用 refs 来更新文本等内容。内容应根据组件的当前 props 和状态呈现。

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

    如果您需要触发子组件上的方法,例如在 TextInput 上调用 focus,但不用于强制更新组件内容,则使用旁注 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}
    />
    

    【讨论】:

    • 哇,我真的想多了。你的答案现在对我来说似乎很明显。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多