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

By [eth.mirror.xyz](https://paragraph.com/@eth-mirror-xyz) · 2021-10-21

---

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

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

> #### static getString()
> 
> 获取剪贴板的文本内容，返回一个Promise语句。
> 
> #### static setString(content: string)
> 
> 设置剪贴板的文本内容。你可以用下面的方式来调用。

    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>
            )
        }
    }
    

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

---

*Originally published on [eth.mirror.xyz](https://paragraph.com/@eth-mirror-xyz/react-native)*
