【问题标题】:React Native Copy the text loaded via API to ClipboardReact Native 将通过 API 加载的文本复制到剪贴板
【发布时间】:2020-12-02 15:27:24
【问题描述】:

我正在从 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;

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    输出:

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

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

    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

    【讨论】:

    • 非常感谢。它就像一个魅力。
    【解决方案2】:

    来自documentation

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

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

    更改您的代码

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

    到这里

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2019-11-23
        • 2011-02-01
        • 2012-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多