首页 > 解决方案 > 使用 React-Native 剪贴板获取 null 不是对象(评估 'u.default.setString')

问题描述

问题

当我在snack.expo.io 中运行以下示例时,出现错误:null is not an object (evaluating 'u.default.setString')

背景

这是我直接取自GitHub 上的示例的确切代码:

应用程序.js:

import React, { useState } from 'react'
import { SafeAreaView, View, Text, TouchableOpacity, StyleSheet } from 'react-native'
import Clipboard from '@react-native-community/clipboard'

export default function App() {
  const [copiedText, setCopiedText] = useState('')

  const copyToClipboard = () => {
    Clipboard.setString('hello world')
  }

  const fetchCopiedText = async () => {
    const text = await Clipboard.getString()
    setCopiedText(text)
  }

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={styles.container}>
        <TouchableOpacity onPress={() => copyToClipboard()}>
          <Text>Click here to copy to Clipboard</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => fetchCopiedText()}>
          <Text>View copied text</Text>
        </TouchableOpacity>

        <Text style={styles.copiedText}>{copiedText}</Text>
      </View>

    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  copiedText: {
    marginTop: 10,
    color: 'red'
  }
})

这是我的 package.json 文件:

{
  "dependencies": {
    "react-native-paper": "3.6.0",
    "@react-native-community/clipboard": "1.2.2"
  }
}

提前谢谢!

标签: javascriptnode.jsreactjsreact-nativeexpo

解决方案


这个库目前不包含在 Expo SDK 中。你可以Clipboard从 React Native 使用:

import { Clipboard } from 'react-native';

推荐阅读