React-Native如何复制文本到剪贴板

React-Native自带Clipboard API,使用Clipboard可以在iOS和Android的剪贴板中读写内容。


官方API里面只有复制到剪贴板和从剪贴板读取内容的两个方法:

static getString()

获取剪贴板的文本内容,返回一个Promise语句。

let  str = Clipboard.getString();

static setString(content: string)

设置剪贴板的文本内容。你可以用下面的方式来调用。

function pasteToClipboard(){
    Clipboard.setString('content')
}

举个栗子:

import React from 'react'
import PropTypes from 'prop-types'
import {
    View,
    Text,
    TouchableWithoutFeedback,
    Clipboard,
} from 'react-native'

export default class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            text:'我是文本'
        }
    }
    async copy(){
        Clipboard.setString(this.state.text);
        let  str = await Clipboard.getString();
        console.log(str)//我是文本
    }
    render() {
        const { text } = this.state;
        return(
              <View>
                  <Text>{text}</Text>
                  <TouchableWithoutFeedback onPress={this.copy.bind(this)}>
                      <View>
                          <Text>点击复制到剪贴板</Text>
                      </View>
                  </TouchableWithoutFeedback>
              </View>
        )
    }
}

目前暂时只支持复制文本和读取文本,实际应用中,我们可能希望能够部分复制,即类似复制从某个位置到某个位置的文本,这个操作如果后续看到的话,我会添加在这后面。

猜你喜欢

转载自blog.csdn.net/xjl271314/article/details/80284602