簡體   English   中英

為什么我的 react-native SearchBar 中的文本沒有更新?

[英]Why isn't the text in my react-native SearchBar updating?

當我輸入時,搜索欄中沒有顯示任何內容,但它知道我正在輸入(來自我的 updateSearch 函數中的打印語句)。 根據我對 react-native searchBar 的理解,我什至不需要做任何事情就可以讓文本顯示在那里,所以我真的不知道我怎么能把它搞砸。 這是一個更大項目的一部分..但我祈禱這個問題與它的其余部分沒有任何關系。

import React, { Component } from "react";
import {
  View,
  Text,
  FlatList,
  ActivityIndicator,
  SafeAreaView,
  StyleSheet
} from "react-native";
import Header from "../components/Header";
import { SearchBar, List, ListItem } from 'react-native-elements';

export default class Search extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      query: "",
      data: []
    };

  }

  renderHeader = () => {
    return (
    <SearchBar
    placeholder="Type Here..."
    onChangeText={this.updateSearch}
    lightTheme={true}
    />
    );
  }

  updateSearch = text => {
    console.log("text", text);
    const formattedSearch = text.toLowerCase();
    this.setState({ query: formattedSearch });
    console.log("text", this.state.query);
  };

  render() {
    return (
      <SafeAreaView style={styles.container}>
        <Header text={"Search"} />
        <FlatList
          ListHeaderComponent={this.renderHeader}
        />
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: Expo.Constants.statusBarHeight
  }
});

所以在你的搜索欄中你可以添加值道具並檢查。

renderHeader = () => {
    return (
    <SearchBar
    placeholder="Type Here..."
    onChangeText={this.updateSearch}
    lightTheme={true}
    value={this.state.query}
    />
    );
  }

所以我相信您將搜索文本存儲為查詢變量。 所以值是 this.state.query。

希望能幫助到你。 詢問您是否有任何疑問。

通過在觸發onChangeText事件時更新值,使您的<SearchBar/>組件成為受控輸入/受控組件。

<SearchBar
    placeholder="Type Here..."
    onChangeText={this.updateSearch}
    value={this.state.query}
    lightTheme={true}
/>

這樣做 - 從性能的角度來看,更新每個新角色的狀態可能會讓您感到擔憂,但這是 React 建議您這樣做的官方方式。 像這樣的受控輸入非常常見。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM