将React Native功能组件转换为类组件

时间:2020-02-03 04:40:13

标签: react-native

我是React Native的新手,在完成了一些教程之后,我一起破解了它,但是现在我想在应用启动时立即加载一些gif,而不是单击按钮后。

进行了一些研究,功能组件似乎无法实现,我需要切换到类组件以使用生命周期函数,例如:

componentWillMount(){
        this.setState({data : inputObject});
    }

到目前为止,我阅读的所有示例在其组件中均未包含函数,因此我无法弄清楚该如何处理它们。因此,如果有可能在应用程序按原样使用该函数时调用一个函数,请让我知道如何(如果没有)如何将该代码转换为类组件样式?谢谢!

import React, {useState} from 'react';
import {
  Dimensions,
  StyleSheet,
  SafeAreaView,
  View,
  Image,
  FlatList,
} from 'react-native';
import SearchInput from './SearchInput';

export default function App() {
  const [allGifResults, setAllGifResults] = useState([]);

  function addSearchResultsHandler(searchTerm) {
    console.log(searchTerm);
    setAllGifResults([]);
    fetchResults(searchTerm);
  }

  function allGifResultsHandler(url) {
    setAllGifResults(currentGifs => [...currentGifs, {id: url, value: url}]);
  }

  function fetchResults(searchTerm) {
    fetch(
      'http://api.giphy.com/v1/gifs/search?q=' +
        searchTerm +
        '&api_key=MKSpDwx7kTCbRp23VtVsP4d0EvfwIgSg&limit=50',
    )
      .then(response => response.json())
      .then(responseJson => {
        for (let item of responseJson.data) {
          allGifResultsHandler(item.images.fixed_height.url);
          console.log(item.images.fixed_height.url);
        }
      })
      .catch(error => {
        console.error(error);
      });
  }

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.screen}>
        <SearchInput onSearchButtonPressed={addSearchResultsHandler} />
      </View>

      <FlatList
        keyExtractor={(item, index) => item.id}
        data={allGifResults}
        numColumns={2}
        renderItem={itemData => (
          <Image
            source={itemData.item.value ? {uri: itemData.item.value} : null}
            style={styles.images}
          />
        )}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  screen: {
    margin: 10,
  },
  images: {
    width: Dimensions.get('window').width / 2 - 20,
    height: Dimensions.get('window').width / 2 - 20,
    margin: 10,
  },
});
import React, {useState} from 'react';
import {
  View,
  TextInput,
  TouchableOpacity,
  Text,
  StyleSheet,
} from 'react-native';

function SearchInput(props) {
  const [searchTerm, setSearchTerm] = useState('');

  function inputHandler(enteredText) {
    setSearchTerm(enteredText);
  }

  return (
    <View style={styles.inputContainer}>
      <TextInput
        placeholder="Search Term"
        style={styles.input}
        onChangeText={inputHandler}
        value={searchTerm}
      />
      <TouchableOpacity
        style={styles.searchButton}
        onPress={props.onSearchButtonPressed.bind(this, searchTerm)}>
        <Text style={styles.searchButtonText}>Search</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  inputContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 20,
  },
  input: {
    width: '70%',
    borderColor: 'black',
    borderWidth: 1,
    fontSize: 16,
  },
  searchButton: {
    height: 50,
    width: 100,
    backgroundColor: 'lightblue',
    marginLeft: 10,
  },
  searchButtonText: {
    height: 50,
    fontSize: 18,
    textAlign: 'center',
    textAlignVertical: 'center',
  },
});

export default SearchInput;

1 个答案:

答案 0 :(得分:1)

    import React, {useState} from 'react';
    import {
      Dimensions,
      StyleSheet,
      SafeAreaView,
      View,
      Image,
      FlatList,
    } from 'react-native';
    import SearchInput from './SearchInput';
    const [allGifResults, setAllGifResults] = useState([]);

    class App extends React.Component {
      constructor(props) {
          super(props);
          this.state = {

          };
        this.addSearchResultsHandler = this.addSearchResultsHandler.bind(this);
        this.allGifResultsHandler = this.allGifResultsHandler.bind(this);
        this.fetchResults = this.fetchResults.bind(this);
      }

      addSearchResultsHandler(searchTerm) {
        console.log(searchTerm);
        setAllGifResults([]);
        fetchResults(searchTerm);
      }

      allGifResultsHandler(url) {
        setAllGifResults(currentGifs => [...currentGifs, {id: url, value: url}]);
      }

      fetchResults(searchTerm) {
        fetch(
          'http://api.giphy.com/v1/gifs/search?q=' +
            searchTerm +
            '&api_key=MKSpDwx7kTCbRp23VtVsP4d0EvfwIgSg&limit=50',
        )
          .then(response => response.json())
          .then(responseJson => {
            for (let item of responseJson.data) {
              allGifResultsHandler(item.images.fixed_height.url);
              console.log(item.images.fixed_height.url);
            }
          })
          .catch(error => {
            console.error(error);
          });
      }
      render(){
         return (
            <SafeAreaView style={styles.container}>
              <View style={styles.screen}>
                <SearchInput onSearchButtonPressed={(data)=> this.addSearchResultsHandler(data)} />
              </View>

              <FlatList
                keyExtractor={(item, index) => item.id}
                data={allGifResults}
                numColumns={2}
                renderItem={itemData => (
                  <Image
                    source={itemData.item.value ? {uri: itemData.item.value} : null}
                    style={styles.images}
                  />
                )}
              />
            </SafeAreaView>
          );
      }
    }

    export default App;

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
      },
      screen: {
        margin: 10,
      },
      images: {
        width: Dimensions.get('window').width / 2 - 20,
        height: Dimensions.get('window').width / 2 - 20,
        margin: 10,
      },
    });

   import React, {useState} from 'react';
import {
  View,
  TextInput,
  TouchableOpacity,
  Text,
  StyleSheet,
} from 'react-native';

const [searchTerm, setSearchTerm] = useState('');
class SearchInput extends React.Component {
  constructor(props) {
      super(props);
      this.state = {

      };
    this.inputHandler = this.inputHandler.bind(this);
  }

  inputHandler(enteredText) {
    setSearchTerm(enteredText);
  }

  render(){
    return (
      <View style={styles.inputContainer}>
        <TextInput
          placeholder="Search Term"
          style={styles.input}
          onChangeText={inputHandler}
          value={searchTerm}
        />
        <TouchableOpacity
          style={styles.searchButton}
          onPress={props.onSearchButtonPressed.bind(this, searchTerm)}>
          <Text style={styles.searchButtonText}>Search</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
export default SearchInput;


const styles = StyleSheet.create({
  inputContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 20,
  },
  input: {
    width: '70%',
    borderColor: 'black',
    borderWidth: 1,
    fontSize: 16,
  },
  searchButton: {
    height: 50,
    width: 100,
    backgroundColor: 'lightblue',
    marginLeft: 10,
  },
  searchButtonText: {
    height: 50,
    fontSize: 18,
    textAlign: 'center',
    textAlignVertical: 'center',
  },
});

export default SearchInput;