简体   繁体   中英

React Native transforming Class to Function

I'm having an incredibly hard time going from a Class to a function and I'm very stumped right now. If I can get help, I would much appreciate it. I deleted render but I'm stumped with how I should alter the state.

Code (currently a Class):

import React, { Component } from 'react'
import { View } from 'react-native'
import SelectMultiple from 'react-native-select-multiple'

const fruits = ['Apples', 'Oranges', 'Pears']
// --- OR ---
// const fruits = [
//   { label: 'Apples', value: 'appls' },
//   { label: 'Oranges', value: 'orngs' },
//   { label: 'Pears', value: 'pears' }
// ]

class App extends Component {
  state = { selectedFruits: [] }

  onSelectionsChange = (selectedFruits) => {
    // selectedFruits is array of { label, value }
    this.setState({ selectedFruits })
  }

  render () {
    return (
      <View>
        <SelectMultiple
          items={fruits}
          selectedItems={this.state.selectedFruits}
          onSelectionsChange={this.onSelectionsChange} />
      </View>
    )
  }
}
export default App

Ideal goal (to a function):

function Fruits ({navigation}) {
  // implementation
}

The following seems to work ( https://snack.expo.io/MBUMn_I8q ):

const fruits = [
  { label: 'Apples', value: 'appls' },
  { label: 'Oranges', value: 'orngs' },
  { label: 'Pears', value: 'pears' }
]

function Fruits ({navigation}) {
  const [selectedFruits, setSelectedFruits] = React.useState([]);

  const onSelectionsChange = newSelections => {
    setSelectedFruits(newSelections);
  }

  return (
      <View>
        <SelectMultiple
          items={fruits}
          selectedItems={selectedFruits}
          onSelectionsChange={onSelectionsChange} />
      </View>
    )
}

You'll use useState to save state instead this.setState . And, at the end of a function component, you just return the view hierarchy.

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