淘口令的核心功能就是用户进入App时读取粘贴板内容,根据粘贴板内容来做出响应。
1、获取粘贴板内容
import { Clipboard } from ‘react-native’;
Clipboard.getString() => Promise 得到粘贴板内容
2、监听App状态,是否进入前台
import { AppState, Clipboard } from ‘react-native’;
AppState.addEventListener(‘change’, handle);
handle = state => { console.log(‘app state is active’,state) };
3、完整代码
自定义hooks,提升复用性,同时处理了对粘贴内容的重复操作
export const useAppStateListener = (props: Props) => {
const clipboardString = useRef(’’);
const stateChangeHandle = useCallback(
async event => {
if (event === ‘active’) {
const path = await Clipboard.getString();
// 防止重复操作
if ( clipboardString.current !== path ) {
clipboardString.current = path;
// do something
}
}
},
[],
);
useEffect(() => {
AppState.addEventListener(‘change’, stateChangeHandle);
return () => {
AppState.removeEventListener(‘change’, stateChangeHandle);
};
}, [stateChangeHandle]);
};
在APP index页调用(务必是函数组件)
06-12
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交