[英]React Native Create Ellipsis Clipped Text in React Native iOS Android or How to make extra text hidden with dots in React native
[英]How to create a custom Text - react native
我現在完成了項目,我想將自定義字體設置為所有Text
組件。
我認為最好的方法是創建一個自定義Text
組件,並將其替換為react-native
默認Text。
現在如何創建具有默認樣式的自定義Text
組件?
為此,您需要有一個react native組件,該組件可在實例化后通過樣式或其他屬性進行配置。
例如,您可以讓您的自定義反應本機組件CustomText
像這樣:
// CustomText.js
import React from 'react';
import {
Text,
StyleSheet,
} from 'react-native';
export default class CustomText extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Text style={[styles.defaultStyle, this.props.style]}>
{this.props.children}
</Text>
);
}
}
const styles = StyleSheet.create({
// ... add your default style here
defaultStyle: {
},
});
然后在您的主要組件上導入並調用該自定義組件,如下所示:
import CustomText from './CustomText';
//... other imports go here.
// in the render method you call your CustomText component.
render(){
//...
<CustomText style={{ fontWeight: 60, }}>
This is custom Text
</CustomText>
}
注意:如果您只想更改樣式,我認為@Yanush解決方案最適合這種情況。
我希望這是有幫助的。
本指南將幫助您如何應用自定義字體,我一直在我的應用程序中使用該方法。 創建自定義文本組件
export default Text = (props)=>{
return(
<Text style={[styles.defaultStyles,props.style]}>{props.children}</Text>
)
}
現在,在您使用過的所有文件中,從react native刪除Text從react native導入並添加
import Text from './path/to/component'
我建議使用樣式而不是自定義組件,但這取決於您。 在我的項目中,我創建了一個名為“ commonStyles.js”的文件,如下所示:
export default StyleSheet.create({
textTitle: {
fontSize: 20,
color: '#dddddd',
fontFamily: 'YourCustomFont',
},
});
然后使用以下方法在需要的地方導入該文件:
import stylesCommon from './styles/stylesCommon';
每個需要更改的文本應如下所示:
<Text style={stylesCommon.textTitle}>
This is my title
</Text>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.