简体   繁体   中英

Unable to Update Array object with a new Textinput data in React Native

I am new to react-native hooks. I am trying to update my array object by whatever the user types in the TextInput field. How can I do it??

where's my state and my folder array object

    const [folder, emptyFolder] = useState([]);

      Array [
  Object {
    "id": "0.017859040901406997",
    "value": "Bar",
  },
]

where's my TextInput. {itemData.item.value} is where I am displaying the name "Bar". I want to update my array with a new array TextInput name. That name is whatever the user enters. Thanks In advance.

    const handlePress = () => {
       ... { map the array[value] an display the new array[value]} ???
      };

<FlatList
    style={{ margin: 2 }}
    data={folderToDisplay}
    //keyExtractor={(item) => item.id}
    numColumns={4}
    renderItem={(itemData) => {
      return (
        <View style={styles.homeRowFolder}>
          <View style={styles.iconAndText}>
              <Text style={styles.textdisplay}>
                {itemData.item.value}
              </Text>
          </View>
        </View>
      );
    }}
  />

I'm not sure what is itemData, I'm supposing is the folder state, in that case I would do something like these.

UPDATE

Use setFolder to update your objects Array:

  const folderContent = [
    {id: '0.017859040901406997', value: 'Bar'},
    {id: '0.017859040901406998', value: 'Mall'},
    {id: '0.017859040901406999', value: '...'},
    {id: '0.017859040901407000', value: '...'},
  ]
  const [folder, setFolder] = useState(folderContent)

Create a folder copy in handlePress function using the new text coming from the TextInput and the array index, and use setFolder to save the new array:

const handlePress = (text, index) => {
    const newFolder = [...folder]
    newFolder[index].value = text

    setFolder(newFolder)
  }

Pass your folder as data to your FlatList . In TextInput call handlePress when onChangeText with the new text and the array index:

        <FlatList
          data={folder}
          keyExtractor={item => item.id}
          renderItem={({item, index}) => {
           return (
              <TextInput onChangeText={text => handlePress(text, index)}>
                {item.value}
              </TextInput>
            )
          }}
        />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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