React Native 将通过 API 加载的文本复制到剪贴板

我正在从 API 获取数据,并且我想在按下复制按钮时复制该文本。

我正在使用 @react-native-community/clipboard

并用 {item.content} 显示数据

我不知道为什么从 api 获得的文本没有复制到剪贴板。

这是我的 app.js 文件。不知道我做错了什么。谢谢。

import React, { useEffect, useState } from "react";
import {
  ActivityIndicator,
  FlatList,
  StyleSheet,
  View,
  Text,
  Button,
} from "react-native";

import Clipboard from '@react-native-community/clipboard';

const App: () => React$Node = () => {

  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [refetch, setRefetch] = useState(false);

  const [copiedText, setCopiedText] = useState('');

  const copyToClipboard = () => {
    Clipboard.setString({item.content});
  };

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

  useEffect(() => {
    fetch("https://exampleapi.com/")
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, [refetch]);

  return (
    <>
      <View style={styles.container}>
        {isLoading ? (
          <ActivityIndicator />
        ) : (
          <FlatList
            data={data}
            keyExtractor={({ id }, index) => id}
            renderItem={({ item }) => (
              <Text style={styles.content}>❝ {item.content} ❞</Text>
            )}
          />
        )}
      </View>
      <View>
        <View style={styles.buttonStyle}>
          <Button
                    title="New"
                    onPress={() => setRefetch(!refetch)}
                    style={styles.buttonCopy}
                    color="#134074"
                  />
        </View>
        <View style={styles.buttonStyle}>
          <Button
                  title="Copy"
                  onPress={() => this.copyToClipboard}
                  style={styles.buttonCopy}
                  color="#aa4465"
                />
        </View>
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: "#001524",
    padding: 30,
    flexDirection: "row",
    alignItems: "center"
  },
  content: {
    fontSize: 25,
    textAlign: "left",
    color: "#ffecd1",
=    padding: 15
  },
  QuotesMark: {
    color: "#ffffff",
    fontSize: 30
  },
  buttonStyle: {
    padding: 10,
    alignItems: "center",
    backgroundColor: "#001524",
  }
});

export default App;
stack overflow React Native Copy the text loaded via API to Clipboard
原文答案
author avatar

接受的答案

输出:

enter image description here

这是完整的工作示例,当您单击 FlatList 项目时,该项目将被复制到剪贴板。我已将复制按钮转换为粘贴按钮以显示粘贴功能。

如果您使用 Expo 制作应用程序,还有一个建议,Expo 仍然不支持 @react-native-community/clipboard ,因此请改用 Clipboard 库中提供的 react-native ,这就是我在以下示例中所做的。

import React, { useEffect, useState } from 'react';
import {
  ActivityIndicator,
  FlatList,
  StyleSheet,
  View,
  Text,
  Button,
  TouchableOpacity,
  TextInput,
  Clipboard,
} from 'react-native';

const App = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [refetch, setRefetch] = useState(false);
  const [selectedText, setSelectedText] = useState('');

  const [copiedText, setCopiedText] = useState(
    'Nothing to show, copy by clicking on FlatList Text, and paste it by clicking Paste button'
  );

  const copyToClipboard = (text) => {
    Clipboard.setString(text);
    console.log('copied to Clipboard');
    fetchCopiedText();
    console.log('copied text: ', copiedText);
  };

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

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, [refetch]);

  return (
    <>
      <View style={styles.container}>
        <TextInput
          style={{
            padding: 10,
            backgroundColor: 'white',
            width: 300,
            color: 'black',
            height: 100,
          }}
        />
        {isLoading ? (
          <ActivityIndicator />
        ) : (
          <FlatList
            data={data}
            keyExtractor={({ id }, index) => id}
            renderItem={({ item }) => (
              <TouchableOpacity
                onPress={() => {
                  Clipboard.setString(item.title);
                  console.log('selected text:', selectedText);
                }}>
                <Text style={styles.content}>❝ {item.title} ❞</Text>
              </TouchableOpacity>
            )}
          />
        )}
      </View>
      <View style={{ width: 300, height: 100 }}>
        <Text>{copiedText}</Text>
      </View>
      <View>
        <View style={styles.buttonStyle}>
          <Button
            title="New"
            onPress={() => setRefetch(!refetch)}
            style={styles.buttonCopy}
            color="#134074"
          />
        </View>
        <View style={styles.buttonStyle}>
          <Button
            title="Paste"
            onPress={() => {
              fetchCopiedText();
            }}
            style={styles.buttonCopy}
            color="#aa4465"
          />
        </View>
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#001524',
    padding: 30,
    flexDirection: 'column',
    alignItems: 'center',
  },
  content: {
    fontSize: 25,
    textAlign: 'left',
    color: '#ffecd1',
  },
  QuotesMark: {
    color: '#ffffff',
    fontSize: 10,
  },
  buttonStyle: {
    padding: 10,
    alignItems: 'center',
    backgroundColor: '#001524',
  },
});

export default App;

工作 Expo Snack Demo


答案:

作者头像

来自 documentation

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

它接收字符串而不是对象。

更改您的代码

 const copyToClipboard = () => {
    Clipboard.setString({item.content});
  };

对此

const copyToClipboard = () => {
    Clipboard.setString(item.content);
  };
作者头像

对于那些在这里使用Expo并在使用 '@react-native-community/clipboard' 时遇到问题的人。切换到 expo-clipboard 请参阅此 documentation