useLinkProps
useLinkProps
Hook 讓我們建立自訂連結元件,可使用路徑而不用依據 linking
選項 的畫面名稱,進而導覽至畫面。它選取路徑,並傳回一個物件,物件中包含你可以傳遞至元件的一些屬性。
範例
import { useLinkProps } from '@react-navigation/native';
// ...
const LinkButton = ({ to, action, children, ...rest }) => {
const { onPress, ...props } = useLinkProps({ to, action });
const [isHovered, setIsHovered] = React.useState(false);
if (Platform.OS === 'web') {
// It's important to use a `View` or `Text` on web instead of `TouchableX`
// Otherwise React Native for Web omits the `onClick` prop that's passed
// You'll also need to pass `onPress` as `onClick` to the `View`
// You can add hover effects using `onMouseEnter` and `onMouseLeave`
return (
<View
onClick={onPress}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
style={{ transitionDuration: '150ms', opacity: isHovered ? 0.5 : 1 }}
{...props}
{...rest}
>
<Text>{children}</Text>
</View>
);
}
return (
<TouchableOpacity onPress={onPress} {...props} {...rest}>
<Text>{children}</Text>
</TouchableOpacity>
);
};
function Home() {
return (
<LinkButton to={{ screen: 'Profile', params: { id: 'jane' } }}>
Go to Jane's profile
</LinkButton>
);
}
之後你可以在應用程式的其他地方使用 LinkButton
元件
function Home() {
return (
<LinkButton to={{ screen: 'Profile', params: { id: 'jane' } }}>
Go to Jane's profile
</LinkButton>
);
}
useLinkProps
傳回的 props
物件包含輔助連結元件所需的屬性。當我們在 View
、Text
等等使用這些屬性時,連結元件會回應使用者動作,例如 Ctrl+Click
/⌘+Click
,這樣可以在新的分頁開啓連結,同時保持一般點擊在同一網頁中。
在 React Native for Web 的目前版本中,使用 useLinkProps
時,有幾項重要的注意事項
- 你必須明確傳遞
onPress
作為onClick
屬性,否則頁面內導覽無法運作 - 你只能將
View
或Text
與useLinkProps
搭配使用。TouchableX
元件不支援我們需要的正確onClick
事件
在 React Native for Web 的未來版本中,這些都不會是問題,而且您可以在 Web、iOS 和 Android 上使用相同的連結碼。但在那之前,您需要為 Web 和原生程式碼撰寫特定於平台的程式碼。
選項
to
您可以傳遞一個具有 screen
屬性的物件
function Home() {
return (
<LinkButton to={{ screen: 'Profile', params: { id: 'jane' } }}>
Go to Jane's profile
</LinkButton>
);
}
此物件的語法與 在嵌套導覽器中導航至畫面 相同。這預設使用 navigate
動作進行導航,除非您指定不同的動作。
或者,您也可以傳遞一個絕對路徑至畫面,例如 - /profile/jane
。
這會用於 href
prop,並用於頁面內導航。
action
有時候我們希望在頁面內導航時具有不同的行為,例如使用 replace
代替 navigate
。我們可以使用 action
prop 來自訂它
範例
import { StackActions } from '@react-navigation/native';
// ...
function Home() {
return (
<LinkButton
to={{ screen: 'Profile', params: { id: 'jane' } }}
action={StackActions.replace('Profile', { id: 'jane' })}
>
Go to Jane's profile
</LinkButton>
);
}
如果沒有指定 action
prop,則會使用提供給 to
prop 的路徑,並將其作為 navigate
動作進行分派。