При нажатии меняется цвет: превращение класса в функцию - PullRequest
0 голосов
/ 24 февраля 2020

Я пытаюсь изменить цвет фона на моем плоском элементе всякий раз, когда нажимаю на строку поиска, чтобы сделать ввод.

Вот полный код SearchScreen. js:

import React, {useState} from 'react';
import { ScrollView, StyleSheet, TextInput, Text, View, FlatList, Keyboard, Image, TouchableOpacity, TouchableWithoutFeedback} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import * as Animatable from 'react-native-animatable';

const listItems = ['Meo Sudoeste', 'Vodafone Paredes de Coura', 'Super Bock Super Rock', 'NOS Primavera Sound', 'Rock in Rio', 'EDP Cool Jazz']

function SearchScreen({navigation}) {

const [searchBarFocused, setSearchBarFocused] = useState(true)

  componentDidMount() {
this.keyboardDidShow = Keyboard.addListener('keyboardDidShow',
this.keyboardDidShow)
this.keyboardWillShow = Keyboard.addListener('keyboardWillShow',
this.keyboardWillShow) 
this.keyboardDidShow = Keyboard.addListener('keyboardWillHide',
this.keyboardWillHide)    
  }

  keyboardDidShow = () => {
    this.setState({ searchBarFocused: true })
  }

  keyboardWillShow = () => {
    this.setState({ searchBarFocused: true })
  }

  keyboardWillHide = () => {
    this.setState({ searchBarFocused: false })
  }


  return (
    <View style={styles.screen}>
  <Animatable.View animation='slideInLeft' duration={500} style={styles.container}>
    <Animatable.View animation={this.state.searchBarFocused ? "fadeInLeft" : "fadeInRight"}>
      <Icon name={this.state.searchBarFocused ? "md-arrow-back" : "ios-search"} style={styles.icon}/>
    </Animatable.View>
    <TextInput style={styles.inputBox}
              underlineColorAndroid='rgba(0,0,0,0)' 
              placeholder="Procura aqui"
              placeholderTextColor = "black"
              selectionColor="black"
              keyboardType="default"/>
  </Animatable.View>
  <View style={styles.teste}> 
    <Text style={styles.festivais}>Recomendados</Text>
    <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={styles.festivais_lista}>

      //I took this off because it is irrelevant

    </ScrollView>
    <FlatList
      style={{backgroundColor:searchBarFocused?'rgba(0,0,0,0.3)':'white'}}
      data = {listItems}
      renderItem={({item}) => <Text style = {{ padding:20, fontSize:20}}>{item}</Text>}
      keyExtractor={(item, index) => index.toString()}
    />
  </View>
</View>
  );
}

SearchScreen.navigationOptions = {
  title: 'Procurar',
};

const styles = StyleSheet.create({

  //I took this off because it is irrelevant

});

export default SearchScreen;

Большая часть кода связана с изменением цвета фона, следует применять к классу, но я не не знаю, как использовать componentDidMount () для функции.

Подскажите, пожалуйста, как мне его кодировать?

ОБНОВЛЕНО

Текущий код с ошибкой Can't find variable: useEffect:

import React, {useState} from 'react';
import { ScrollView, StyleSheet, TextInput, Text, View, FlatList, Keyboard, Image, TouchableOpacity, TouchableWithoutFeedback} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import * as Animatable from 'react-native-animatable';

const listItems = ['Meo Sudoeste', 'Vodafone Paredes de Coura', 'Super Bock Super Rock', 'NOS Primavera Sound', 'Rock in Rio', 'EDP Cool Jazz']

function SearchScreen({navigation}) {

  const [searchBarFocused, setSearchBarFocused] = useState(true)

  useEffects(() => {
keyboardDidShow = Keyboard.addListener('keyboardDidShow',
keyboardDidShow)
keyboardWillShow = Keyboard.addListener('keyboardWillShow',
keyboardWillShow) 
keyboardDidShow = Keyboard.addListener('keyboardWillHide',
keyboardWillHide)    
   }, [])

  keyboardDidShow = () => {
setSearchBarFocused(true) 
  }

  keyboardWillShow = () => {
setSearchBarFocused(true)
  }

  keyboardWillHide = () => {
setSearchBarFocused(false)
  }

  return (
<View style={styles.screen}>
  <Animatable.View animation='slideInLeft' duration={500} style={styles.container}>
    <Animatable.View animation={searchBarFocused ? "fadeInLeft" : "fadeInRight"}>
      <Icon name={searchBarFocused ? "md-arrow-back" : "ios-search"} style={styles.icon}/>
    </Animatable.View>
    <TextInput style={styles.inputBox}
              underlineColorAndroid='rgba(0,0,0,0)' 
              placeholder="Procura aqui"
              placeholderTextColor = "black"
              selectionColor="black"
              keyboardType="default"/>
  </Animatable.View>
  <View style={styles.teste}> 
    <Text style={styles.festivais}>Recomendados</Text>
    <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={styles.festivais_lista}> 

 //It's irrelevant

    </ScrollView>
    <FlatList
      style={{backgroundColor:searchBarFocused?'rgba(0,0,0,0.3)':'white'}}
      data = {listItems}
      renderItem={({item}) => <Text style = {{ padding:20, fontSize:20}}>{item}</Text>}
      keyExtractor={(item, index) => index.toString()}
    />
  </View>
</View>
  );
}

SearchScreen.navigationOptions = {
  title: 'Procurar',
 };

    const styles = StyleSheet.create({
      //It's irrelevant
    });

    export default SearchScreen;

Как мне это исправить?

1 Ответ

0 голосов
/ 24 февраля 2020

Жизненные циклы компонентов класса, такие как componentDidMount, не существуют в функциональных компонентах. Замените их на useEffects (). И this также не существует в функциях. Он существует, но не ведет себя так, как вы думаете.


  const [searchBarFocused, setSearchBarFocused] = useState(true)

  useEffects(() => {
   keyboardDidShow = Keyboard.addListener('keyboardDidShow',
   keyboardDidShow)
   keyboardWillShow = Keyboard.addListener('keyboardWillShow',
   keyboardWillShow) 
   keyboardDidShow = Keyboard.addListener('keyboardWillHide',
   keyboardWillHide)    
  }, []) // empty dependencies means it will run only once at the start 


...

  // Update the state using only hooks
  setSearchBarFocused(<value>) // instead of this.setState(<blah blah>)
...

Вспомните все, что вы узнали из OOP, и выбросьте его в окно. Нет this this.setState жизненных циклов компонентов. Все это просто чистые функции - точно так, как задумал Бог до того, как OOP пришел и все разрушил.


Эта статья будет хорошим началом для перехода от объектно-ориентированного программирования (компоненты класса) к функциональному программированию (функциональные компоненты)

https://overreacted.io/how-are-function-components-different-from-classes/

...