[英]How to call function from different component bound to flatlist in React Native
我正在React Native中創建一個聊天應用程序,該應用程序接收不同的“消息類型”作為響應。 其中一個包含一系列按鈕,這些按鈕目前正在組件“ ChatQuickReply”的Flatlist中呈現,如下所示:
import React from "react";
import {
StyleSheet,
FlatList,
View,
TouchableOpacity,
Text
} from "react-native";
class ChatQuickReply extends React.Component {
constructor(props) {
super(props);
}
renderItem({ item }) {
return (
<TouchableOpacity onPress={this._onPressQuickReply}>
<View style={styles.quickButton}>
<Text style={styles.quickButtonText}>{item.title}</Text>
</View>
</TouchableOpacity>
);
}
_onPressQuickReply = () => {
alert(Hello);
};
render() {
return (
<View>
<FlatList
data={this.props.buttons}
keyExtractor={(item, index) => "key" + index}
renderItem={this.renderItem}
/>
</View>
);
}
}
我在Flatlist中的另一個組件中渲染此組件,效果很好。
問題是,我無法調用分配給TouchableOpacity的函數。 如何從其他組件調用此函數?
我認為,您可以嘗試觸發TouchableOpacity組件的onPress事件。
您需要為此的參考。
ref={touchableOpacity => this._touchableOpacity = touchableOpacity}
然后,當您要啟動onPress而不單擊它時,只需調用
this._touchableOpacity.touchableHandlePress();
根據兩個組件之間的關系,如果ChatQuickReply答復是父組件,則可以將子對象中的函數作為道具傳遞並調用它。
import React from "react";
class ChatQuickReply extends React.Component {
renderItem({ item }) {
return (
<TouchableOpacity onPress={this._onPressQuickReply}>
<View style={styles.quickButton}>
<Text style={styles.quickButtonText}>{item.title}</Text>
</View>
</TouchableOpacity>
);
}
_onPressQuickReply = () => {
alert(Hello);
};
render() {
return (
<View>
<FlatList
data={this.props.buttons}
keyExtractor={(item, index) => "key" + index}
renderItem={this.renderItem}
/>
**<ChildComponent clickParentFunction={this._onPressQuickReply} />**
</View>
);
}
}
class ChildComponent extends React.Component {
onClick = () => {
const {clickParentFunction} = this.props
clickParentFunction() // We can call it here
}
// We create a trigger to the onclick
}
或者,您可以將_onPressQuicklyReply函數帶給呈現兩個組件的組件,然后將其傳遞以使其更通用
import OtherComponent from './Othercomponent';
class ParentComponent {
_onPressQuickReply = () => {
alert(Hello);
}
return (
<View>
<ChatQuicklyReply onParentFunction={this._onPressQuickly}>
<OtherComponent onParentFunctionCall={this._onPressQuickly} />
</View>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.