写一段 react natice NFC P2P模式的收发代码
时间: 2024-03-18 16:40:15 浏览: 17
好的,以下是一个简单的React Native NFC P2P模式收发代码示例:
```
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import NfcManager, { NfcTech, Ndef } from 'react-native-nfc-manager';
export default class App extends Component {
state = {
message: '',
};
componentDidMount() {
NfcManager.start();
NfcManager.setEventListener(NfcManager.EVENT_NDEF_DISCOVERED, this.onNfcReceived);
}
componentWillUnmount() {
NfcManager.setEventListener(NfcManager.EVENT_NDEF_DISCOVERED, null);
NfcManager.stop();
}
onNfcReceived = async (tag) => {
const ndef = await NfcManager.ndefHandler.parseUri(tag.ndefMessage[0].payload);
this.setState({ message: ndef });
};
sendNfcMessage = async () => {
try {
await NfcManager.requestTechnology(NfcTech.Ndef, {
alertMessage: 'Ready to send NFC message',
});
const bytes = Ndef.encodeMessage([Ndef.textRecord('Hello, world!')]);
await NfcManager.ndefHandler.writeNdefMessage(bytes);
NfcManager.cancelTechnologyRequest();
} catch (error) {
console.warn('Error sending NFC message', error);
}
};
render() {
return (
<View>
<Text>{this.state.message}</Text>
<Button title="Send NFC Message" onPress={this.sendNfcMessage} />
</View>
);
}
}
```
这个示例使用`react-native-nfc-manager`库来监听NFC P2P事件并接收NFC消息。当用户点击“Send NFC Message”按钮时,它将发送一条包含“Hello, world!”文本的NFC消息。这只是一个简单的示例,您可以根据自己的需求来修改和扩展代码。