在React Native Webview中使用自定义字体 [英] Using custom fonts in React native Webview
问题描述
我在整个React本机应用程序中使用自定义字体。我已经使用react-native link命令链接了它们。它们可以在Android的Webview组件内的任何地方工作。
I'm using custom fonts in my entire React native application. I have linked them using react-native link command. They work everywhere except inside the Webview component of Android. It works properly in iOS Webview.
import React, { Component } from "react"
import { View, StyleSheet, Text, WebView, ScrollView, Image } from "react-native"
import HTMLView from "react-native-htmlview"
export class PostDetailPage extends Component {
static navigationOptions = {
title: ({ state }) => state.params.post.title,
header: {
style: {
backgroundColor: '#FF9800',
},
titleStyle: {
color: 'white',
fontFamily: "Ekatra",
fontWeight: "normal"
},
tintColor: 'white'
}
}
constructor(props) {
super(props)
}
render() {
const post = this.props.navigation.state.params.post
const html = `
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
font-family: Lohit-Gujarati;
font-size: 1.25rem;
color: black;
padding: 0px 10px 10px 10px;
}
p {
text-align: justify;
}
</style>
</head>
<body>
${post.content}
</body>
</html>
`
return (
<View style={{ flex: 1, overflow: "visible" }}>
<Image source={{ uri: post.featured_image }} style={{ height: 150 }} />
<WebView
source={{html}}
style={{flex: 1}}
/>
</View>
)
}
}
我尝试用url( file:/// android_assets / fonts / Lohit-Gujarati)在webview CSS内创建字体。没用导入谷歌字体CSS的作品。在React Native Android Webview中使用本地自定义字体的正确方法是什么?
I have tried creating a font-face inside the webview css with url("file:///android_assets/fonts/Lohit-Gujarati"). It doesn't work. Importing google fonts css works. What is the right way to use local custom fonts in React native Android Webview?
推荐答案
在webview CSS中创建字体如果在WebView上设置了baseUrl,则使用url( file:/// android_asset / fonts / Lohit-Gujarati)即可:
Creating a font-face inside the webview css with url("file:///android_asset/fonts/Lohit-Gujarati") works if baseUrl is set on WebView:
<WebView
source={{html, baseUrl: 'someUrl'}}
style={{flex: 1}}
/>
我不确定为什么没有baseUrl不能正常工作,但我认为可能是因为缺少baseUrl时,RN使用另一种方法加载WebView:
I'm not sure why it doesn't work without baseUrl, but I think it can be because RN uses a different method to load the WebView when baseUrl is missing:
if (source.hasKey("baseUrl")) {
view.loadDataWithBaseURL(
source.getString("baseUrl"), html, HTML_MIME_TYPE, HTML_ENCODING, null);
} else {
view.loadData(html, HTML_MIME_TYPE, HTML_ENCODING);
}
这篇关于在React Native Webview中使用自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!