【问题标题】:Trigger an onPress Function from anonther component从另一个组件触发 onPress 函数
【发布时间】:2021-05-04 22:42:50
【问题描述】:

我想从导航栏中的搜索图标触发 onPress 功能。 这是搜索组件:

function SearchIcon(props) {
  const theme = useSelector(state => state.themer.theme);
  return (
    <Icon.Button
      name="search"
      size={22}
      color={theme.icons}
      backgroundColor={theme.top_tab}
      onPress={() => {}}
    />
  );
}

export default SearchIcon;

搜索组件正在特定堆栈中被调用。

<Stack.Screen
        name="Home"
        component={Home}
        options={({navigation, route}) => ({
          ...,
          headerRight: props => (
            <View style={{flexDirection: 'row'}}>
              <SearchIcon  />
              <CartIcon navigation={navigation} />
            </View>
          ),
        })}
      />

在主屏幕上,我有一个 isSeacrhing 常量,它应该将值从 false 更改为 true,反之亦然。

const [data, setData] = React.useState({
    isSearching: false,
    search: '',
...
  });

  // TRIGGERED BY SEARCH ICON IN NAV BAR
  const toggleSearch = () => setData({...data, isSearching: !isSearching});

{data.isSearching == false ? (
          <ScrollView
            ...
          </ScrollView>
        ) : (
          <View>
            <TextInput
              style={[styles.textInput, [{color: theme.text, ...FONTS.body4}]]}
              value={data.search}
              placeholder="Search..."
              placeholderTextColor={theme.text}
              onChangeText={()=>{}}
            />
          </View>
        )}

是否可以触发onPress 功能,或者有其他方法可以让它工作吗?搜索图标在两个屏幕上,调用相同的函数会使TextInput 出现在两个屏幕上吗?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    无论你在哪里使用&lt;SearchIcon /&gt;,只需在其中添加一个像这样的道具

    <SearchIcon onPress={() => { // Do Something }} />
    

    然后在你的SearchIcon

    function SearchIcon(props) {
      const theme = useSelector(state => state.themer.theme);
      return (
        <Icon.Button
          name="search"
          size={22}
          color={theme.icons}
          backgroundColor={theme.top_tab}
          onPress={props.onPress} // Access it here like this
        />
      );
    }
    
    export default SearchIcon;
    

    【讨论】:

    • 我认为如果在显示的屏幕内调用&lt;SearchIcon/&gt;,但它是在 上调用的,则此解决方案将起作用。我不知道如何将toggleSearch 传递给onPress 函数。
    • 抱歉,在找到 useLayoutEffect 钩子并使用 react-navigation 中的 navigation.setOptions 之前,我不知道如何应用您的解决方案。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2021-08-15
    • 2017-08-11
    • 1970-01-01
    相关资源
    最近更新 更多