你如何从 react-native 的子组件(带参数)调用父函数?

我有一个名为 HomeHeader 的 React 组件。HomeHeader 中有一个名为 SearchResultFlatList 的无状态组件。SearchResultFlatList 中有一个名为 SearchListItem 的无状态组件。HomeHeader 有 2 个输入字段(一个用于位置,一个用于目的地)。在输入字段中输入后,SearchResultFlatList 将被创建并重新填充 SearchListItems(每次我输入内容时(想想谷歌搜索))。单击 SearchListItem 时,我希望能够调用驻留在 HomeHeader 上的函数。要实现的功能是单击 SearchListItem,并在 HomeHeader 上填充相应的输入字段。


我在 HomeHeader 上声明了一个名为 onLocationPress 的函数。它接受一个参数(即 onLocationPress(locationValue))。将对此函数的引用传递给子组件非常简单,但是当涉及到变量时变得更加困难。


来自 HomeHeader.js


<SearchResultFlatList

   containerOpacity={this.state.opacityProp}

   headerExpanded={this.state.headerExpanded}

   results={this.props.searchResults}

   clickLocationResult={this.onLocationPress}

/>

来自 SearchResultFlatList.js


const SearchResultFlatList = (props) => {

    return(

        <Animated.View>

        <FlatList

          ....

            <SearchListItem

                clickLocationResult={props.clickLocationResult}

                primaryText={item.primaryText}

                fullText={item.fullText}

            />)}

          ....

        />

    </Animated.View>

    )

}

来自 SearchListItem.js


const SearchListItem = (props) => {


    return (

        <TouchableOpacity 

            style={styles.searchListItemContainer}

            onPress={props.clickLocationResult(props.primaryText)}

        >

        ....

        </TouchableOpacity>

    );

  }

以这种方式调用它会导致函数被多次调用。我onTextChanged()在输入字段上也有一个函数,每次我输入它都会记录props.primaryText值。


我认为这与每次键入时都会创建新的 SearchListItems 的事实有关,但我不知道解决方法。


达令说
浏览 195回答 2
2回答

GCT1015

您不能将带有参数的函数传递给 onPress。而是定义一个箭头函数,该函数使用像这样的参数来执行您的 clickLocationResult。const SearchListItem = props => {&nbsp; return (&nbsp; &nbsp; <TouchableOpacity&nbsp; &nbsp; &nbsp; style={styles.searchListItemContainer}&nbsp; &nbsp; &nbsp; onPress={() => props.clickLocationResult(props.primaryText)}&nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; ....&nbsp; &nbsp; </TouchableOpacity>&nbsp; );};

智慧大石

你能在 HomeHeader 中发布你的 onLocationPress 函数吗?我怀疑你需要的是所谓的函数柯里化。有很多关于此的资源,但基本思想是您的函数将被定义为:function onLocationPress(text) {&nbsp; &nbsp; // this is your click handler&nbsp; &nbsp; return () => {&nbsp; &nbsp; &nbsp; &nbsp; // do something with that text&nbsp; &nbsp; }}当您为 onPress 处理程序提供带有参数的函数时,该函数正在执行,结果将返回给处理程序,而不是函数本身。你想要的是 onLocationPress 成为一个返回另一个函数的函数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript