【发布时间】:2023-03-27 02:48:01
【问题描述】:
在 onMasterClicked 方法中,我想使用 web-socket 连接并向服务器发送数据。
我更喜欢使用 react-native 的本地 web 套接字库,我也可以使用 socket.io 客户端,但这对我不起作用。我不需要应用程序中的服务器端代码,服务器是云。
只想知道如何使用 web-socket 连接到服务器并发送数据,并在向应用程序发送数据时监听它
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, TouchableOpacity } from 'react-native';
import Card from '../common/Card';
import { onMasterClicked } from '../../actions';
class MasterCard extends Component {
getMasterUnit() {
return this.props.masterUnit;
}
masterClicked() {
const cardNav = this.props.masterCardNav;
this.props.onMasterClicked(this.getMasterUnit());
cardNav('Room', {
id: this.getMasterUnit().id,
title: this.getMasterUnit().title,
});
}
render() {
return (
<TouchableOpacity onPress={this.masterClicked.bind(this)}>
<Card>
<View style={styles.parentContainer}>
<Text style={styles.masterNameTextStyles}> { this.getMasterUnit().title } </Text>
<Text style={styles.arrowTextStyle}> > </Text>
</View>
</Card>
</TouchableOpacity>
);
}
}
const styles = {
parentContainer: {
flexDirection: 'row',
flex: 1,
alignItems: 'center',
height: 50
},
masterNameTextStyle: {
flex: 1,
textAlign: 'left',
color: '#000000',
fontSize: 16,
textAlignVertical: 'center'
},
arrowTextStyle: {
flex: 1,
textAlign: 'right',
color: '#000000',
fontSize: 16,
textAlignVertical: 'center'
}
};
export default connect(null, { onMasterClicked })(MasterCard);
【问题讨论】:
-
这个guide 应该是合适的。它使用来自 NPM 的
socket.io-client。