https://reactnative.dev/docs/share
공식문서
const Detail: React.FC<DetailScreenProps> = ({
navigation: { setOptions },
route: { params },
}) => {
const { isLoading, data, refetch } = useQuery(
['movies', params.id],
moviesApi.detail,
{ enabled: 'original_title' in params }
)
const isMovie = 'original_title' in params
const shareMedia = async () => {
const isAndroid = Platform.OS === 'android'
const homePage = isMovie
? `https://www.imdb.com/title/${data.imdb_id}/`
: data.homepage
if (isAndroid) {
await Share.share({
message: `${params.overview}\nCheck it out: ${homePage}`,
title: params.original_title,
})
} else {
await Share.share({
url: homePage,
message: params.overview,
title: params.original_title,
})
}
}
const ShareButton = () => (
<TouchableOpacity onPress={shareMedia}>
<Ionicons name="share-outline" color="white" size={24} />
</TouchableOpacity>
)
useEffect(() => {
setOptions({
title: params.original_title,
})
}, [])
useEffect(() => {
if (data) {
setOptions({
headerRight: () => <ShareButton />,
})
}
}, [data])
const openTYLink = async (videoID: string) => {
const baseUrl = `http://m.youtube.com/watch?v=${videoID}`
await Linking.openURL(baseUrl)
}~~~~
1. shareButton 만들기
const ShareButton = () => (
<TouchableOpacity onPress={shareMedia}>
<Ionicons name="share-outline" color="white" size={24} />
</TouchableOpacity>
)
2. useEffect이용해서 setOptions의 headerRight부분에 버튼 넣기
data가 loading 됬을떄에만, 버튼이 보이게 설정함.
useEffect(() => {
if (data) {
setOptions({
headerRight: () => <ShareButton />,
})
}
}, [data])
3. onPress={shareMedia}의 shareMedia 함수 만듬.
import {
Dimensions,
StyleSheet,
Linking,
TouchableOpacity,
Share,
Platform,
} from 'react-native'
const isMovie = 'original_title' in params
const shareMedia = async () => {
const isAndroid = Platform.OS === 'android'
const homePage = isMovie
? `https://www.imdb.com/title/${data.imdb_id}/`
: data.homepage
if (isAndroid) {
await Share.share({
message: `${params.overview}\nCheck it out: ${homePage}`,
title: params.original_title,
})
} else {
await Share.share({
url: homePage,
message: params.overview,
title: params.original_title,
})
}
check!! \n은 줄바꿈임
android에는 url을 보낼수 없기때문에(ios만 가능)
message에 homepage를 담아서 보냄.