简体   繁体   中英

React native render component based on TextInput onfocus

I want to display something in my react component when user clicks into a text input (something similar to Instagram's search, where if you click on their input field, a search component suggestion shows up.

const SearchScreen = props => {

  const renderSearch = () => {
    return (
      <>
       // need to display the search suggestion
      </>
    )
  }

  return (
    <>
      <TextInput
        placeholder="Search"
        onChangeText={text => handleChange(text)}
        value={searchText}
        onFocus={() => renderSearch()} // based on focus, then render component
      />
      <View>
        // how do I render here?
        // this will render on load, but need to render onFocus
        {renderSearch}
      </View>
    </>
  );
};

You can apply a similar pattern than stackoverflow.com/a/34091564/1839692.

For instance you can try something like :

const SearchScreen = props => {
  const [searchFocus, setSearchFocus] = useState(false)

  const renderSearch = () => {
    return (
      <>
       // need to display the search suggestion
      </>
    )
  }

  return (
    <>
      <TextInput
        placeholder="Search"
        onChangeText={text => handleChange(text)}
        value={searchText}
        onFocus={() => setSearchFocus(true)}
        onBlur={() => setSearchFocus(false)}
      />
      { searchFocus 
        ? <View>
            {renderSearch}
          </View> 
        : <View>
            // Add here the code to display when not searching
          </View>
      }

    </>
  );
};

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