按下搜索图标后如何展开搜索栏

时间:2018-07-29 06:16:45

标签: javascript reactjs react-native

我以某种方式通过组件创建了一个搜索图标,我只是想知道当有人按下搜索栏图标时如何展开它。.

  import { TouchableOpacity,View, Image} from 'react-native';
  import { SearchBar } from 'react-native-elements';
  export default class Search extends Component{
     onClick(){
      return <SearchBar/> // [![Seach Image][1]][1]not working
}

render(){
    // not worrking
    let search = <SearchBar/>;
    return(
        <View>
            <TouchableOpacity
                onPress={() => {
                    return search
                }}
            >
                <Image
                    source={require('../images/tabs/search.png')}
                    style={{height: 40, width: 60}}
                    resizeMode={'contain'}
                />
            </TouchableOpacity>
        </View>
     )
   }
 }

SearchImage

1 个答案:

答案 0 :(得分:1)

您应该在组件中添加状态以控制标题的行为

import { TouchableOpacity, View, Image } from 'react-native';
import { SearchBar } from 'react-native-elements';
export default class Search extends Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
    this.state = {
      showSearchBar: false, // control what ever to render the searchbar or just the icon
    };
  }
  onClick() {
    let { showSearchBar } = this.state;
    this.setState({
      showSearchBar: !showSearchBar,
    });
  }

  render() {
    const { showSearchBar } = this.state;
    return (
      <View>
        {!showSearchBar ? (
          <TouchableOpacity onPress={this.onClick}>
            <Image
              source={require('../images/tabs/search.png')}
              style={{ height: 40, width: 60 }}
              resizeMode={'contain'}
            />
          </TouchableOpacity>
        ) : (
          <SearchBar />
        )}
      </View>
    );
  }
}