我正在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();
根据两个组件之间的关系,Chat Quick Reply回复是一个父组件,您可以将子组件中的函数作为props传递并调用它。
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>
)
}