【问题标题】:React Native - Add search bar in the headerReact Native - 在标题中添加搜索栏
【发布时间】:2019-08-11 23:48:36
【问题描述】:

我想在右侧的标题中添加一个搜索按钮。按下时,标题中会出现一个搜索栏。

我尝试使用 react-navigation 的 setParams() 函数,但出现错误。

我的代码:

    static navigationOptions = ({ navigation }) => {
        return {
            headerRight: (
                navigation.getParam('search') === 1 ?
                <TouchableOpacity onPress={navigation.getParam('searchBar')} style={{ marginHorizontal: 10 }}>
                    <FontAwesome name="search" size={28} color="white" />
                </TouchableOpacity>
                :
                <Text>My Search Bar</Text>
            )
        };
    };

    test() {
        this.props.navigation.setParams({searchBar: 0});
    }

    componentDidMount() {
        this.props.navigation.setParams({search: 1, searchBar: this.test})
    }

componentDidMount() 函数中的代码有效。但不是测试功能中的那个。

我收到以下错误消息:未定义不是对象(正在评估 'this.props.navigation')

我想要的结果是,当我按下“搜索”按钮时,出现文本“确定”

【问题讨论】:

  • 为什么要在右边的header中放一个条件语句?
  • @hongdevelop 因为如果用户没有按下按钮,我会留下图标显示。如果他按下它,我会更改显示并放置一个搜索栏。

标签: react-native


【解决方案1】:

我认为这是更改值的简单错误。您必须更改搜索值才能更改您想要的值。


      static navigationOptions = ({ navigation }) => {
        return {
           headerTitle: <LogoTitle />,
            headerRight: (
                navigation.getParam('search') === 1 ?
                <TouchableOpacity onPress={() => navigation.setParams({search: 0})} style={{ marginHorizontal: 10 }}>
                     <FontAwesome name="search" size={28} color="white" />
                </TouchableOpacity>
                :
                <Text>My Search Bar</Text>
            )
        };
    };

    componentDidMount() {
        this.props.navigation.setParams({search: 1, searchBar: this.test})
    }

【讨论】:

  • 我不能在 navigationOptions 中使用 this.state(文档:reactnavigation.org/docs/en/header-buttons.html
  • @Mat 我认为这是更改值的简单错误。您必须更改搜索值才能更改您想要的值。
  • 我把问题放在了错误的一边......它的工作,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
相关资源
最近更新 更多