簡體   English   中英

檢測本機文本輸入中的粘貼事件

[英]Detect a paste event in a react-native text input

我想粘貼到本機輸入中,但根據粘貼的內容做一些事情(即,如果粘貼的內容是鏈接,則相應地設置樣式)。 但是,為了做到這一點,我需要知道何時將某些內容粘貼到文本輸入中。 我不確定如何監聽粘貼事件。 剪貼板在這里並沒有真正的幫助,因為它所做的只是設置/獲取內容,而不是告訴我是否粘貼了一些任意內容。

對於那些從谷歌看到這篇文章的人,並沒有像我一樣幸運,幸運的是,我找到了解決方案,雖然並不理想,因為它使用了onChangeText事件。

想法很簡單,每次修改文本時,我都會將其與剪貼板中的內容進行比較。 就是這樣。

最小的示例代碼

export default class App extends React.Component {
  handleOnPaste = (content) => {
    alert('paste detected! content: '.concat(content));
  }

  handleOnChangeText = async (content) => {
    if (content === '') return;
    const copiedContent = await Clipboard.getString();
    
    if (copiedContent === '') return;
    const isPasted = content.includes(copiedContent);
    if (isPasted) this.handleOnPaste(content);
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput 
          placeholder={'fill something'} 
          style={styles.input} 
          onChangeText={this.handleOnChangeText} 
        />
      </View>
    );
  }
}

這里是 小吃博覽會,享受!

在此處輸入圖片說明

您可以在 state 中保留 2 個輸入副本,其中 1 個副本是輸入的先前狀態,另一個副本是當前輸入的狀態。 例子是

Actual input: asd
this.state={copy_one: "as", copy_two: "asd"}

Actual input: asdgoogle.com
this.state={copy_one: "asd", copy_two: "asdgoogle.com"}

您可以通過執行更新它們

this.setState({copy_one: this.state.copy_two, copy_two: currentValue})

在 onChange 道具的每個觸發器上。 如果您專門尋找更改,則可以通過替換刪除原始字符串來獲得差異的快速而骯臟的技巧

difference = this.state.copy_two.replace(this.state.copy_one, "")

那么你可以使用正則表達式來查看它是否是一個鏈接並相應地對其進行樣式化。

為了檢測過去的事件,在 react-native 中,我的解決方案基於應用程序狀態工作。 因此,如果應用程序在后台,則意味着該應用程序處於非活動狀態(用戶可能正在復制),否則它將處於非活動模式(此處我們可以檢查用戶是否進行了復制操作) 請先從這里添加此剪貼板模塊

import React, {useEffect, useRef, useState} from 'react'
import Clipboard from '@react-native-community/clipboard';
import { View Text, TextInput} from "react-native"
export default const ScreenToPastIn = () => { 

const [pastContent,setPastContent] = useState('')

 useEffect(() => {
    AppState.addEventListener('change', handleAppStateChange);
    return () => {
        AppState.removeEventListener('change', handleAppStateChange);
    };
}, []);

  const handleAppStateChange = (nextAppState) => {
  
     if(nextAppState == 'active')
     {

         Clipboard.getString().then((content) => {
             if(content && content.length>0)
             {
                  
                 setPastContent(content)
             }

         }).catch(e=>{
             setError('incorrect code')
         })
     }

};
return <View>
<Text>{pastContent}</Text>
<TextInput value = {pastContent} ><TextInput>
</View>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM