ReactJS 网页字体
ReactJS web font
我的网络字体有问题。
我从 api 得到字体 link 。如何在渲染方法中使用该字体?
componentDidMount() {
axios.get(URL_FONT)
.then((resp) => {
this.setState({
fontData: resp.data.data
});
}).catch(() => {
console.log("Error_006");
});
}
render(){
return(
{ this.state.fontData.map((item, index)=>{
<span key={index} style={{fontFamily: item.name}}>
{item.name}
</span>
})
)
}
实际问题是 - 有没有办法动态使用@font-face?
@font-face {
font-family: myFirstFont;
src: url(sansation_light.woff);
}
您可以使用WebFontLoader
动态设置字体:
我正在找到答案(来源 使用 Javascript 动态加载字体
)
const addFont = new FontFace(
yorFontName, yorFontUrl,
{"font-display": "block", weight: "normal"} // odere props
);
addFont.load()
.then(function (loaded_face) {
document.fonts.add(loaded_face);
})
.catch(function (error) {
console.log(error);
});
@Tigrank 解决方案适用于 CDN 字体(如 Google 字体),但如果您想在代码中使用它们而不是 CDN 字体,(某些项目 运行 虽然无法访问互联网, 那么资源必须可以通过内部网络访问)
- 在
src
中创建一个 fonts
目录
- 将您的字体文件复制到
fonts
- 在
index.js
import './fonts/FontFILE.ttf';
其他字体格式也适用(wof/wof2/svg).
- 对所有字体重复第 3 步
- 为每个字体文件添加此 CSS 代码:
/* FONT NAME */
@font-face {
font-family: 'FONT_NAME';
src:
url('../fonts/FONT-NAME.ttf') format('truetype');
/*
For other font file formats:
src:
url('../fonts/WOF2-Font.woff2') format('woff2'),
url('../fonts/WOF-Font.woff') format('woff'),
url('../fonts/TTF-Font.ttf') format('truetype');
*/
font-weight: normal;
font-style: normal;
}
- 也对每个字体文件重复第 5 步。
我的网络字体有问题。 我从 api 得到字体 link 。如何在渲染方法中使用该字体?
componentDidMount() {
axios.get(URL_FONT)
.then((resp) => {
this.setState({
fontData: resp.data.data
});
}).catch(() => {
console.log("Error_006");
});
}
render(){
return(
{ this.state.fontData.map((item, index)=>{
<span key={index} style={{fontFamily: item.name}}>
{item.name}
</span>
})
)
}
实际问题是 - 有没有办法动态使用@font-face?
@font-face {
font-family: myFirstFont;
src: url(sansation_light.woff);
}
您可以使用WebFontLoader
动态设置字体:
我正在找到答案(来源 使用 Javascript 动态加载字体 )
const addFont = new FontFace(
yorFontName, yorFontUrl,
{"font-display": "block", weight: "normal"} // odere props
);
addFont.load()
.then(function (loaded_face) {
document.fonts.add(loaded_face);
})
.catch(function (error) {
console.log(error);
});
@Tigrank 解决方案适用于 CDN 字体(如 Google 字体),但如果您想在代码中使用它们而不是 CDN 字体,(某些项目 运行 虽然无法访问互联网, 那么资源必须可以通过内部网络访问)
- 在
src
中创建一个 - 将您的字体文件复制到
fonts
- 在
index.js
import './fonts/FontFILE.ttf';
其他字体格式也适用(wof/wof2/svg). - 对所有字体重复第 3 步
- 为每个字体文件添加此 CSS 代码:
fonts
目录
/* FONT NAME */
@font-face {
font-family: 'FONT_NAME';
src:
url('../fonts/FONT-NAME.ttf') format('truetype');
/*
For other font file formats:
src:
url('../fonts/WOF2-Font.woff2') format('woff2'),
url('../fonts/WOF-Font.woff') format('woff'),
url('../fonts/TTF-Font.ttf') format('truetype');
*/
font-weight: normal;
font-style: normal;
}
- 也对每个字体文件重复第 5 步。