我现在完成了我的项目,我想将我的自定义字体设置为所有 Text
组件。
我认为最好的方法是创建一个自定义的 Text
组件并将其替换为 react-native
的默认 Text。
现在如何创建具有默认样式的自定义 Text
组件?
最佳答案
为此,您需要有一个 React 原生组件,该组件在实例化后可通过样式或其他属性进行配置。
例如,您可以像这样让您的自定义 React native 组件 CustomText
:
<强>1。功能组件
如果你更喜欢新的方式并且你将使用它与钩子(Hook),使用这个部分:
// CustomText.js
import React from 'react';
import {
Text,
StyleSheet,
} from 'react-native';
export default function CustomText(props) {
return (
<Text style={[styles.defaultStyle, props.style]}>
{props.children}
</Text>
);
}
const styles = StyleSheet.create({
// ... add your default style here
defaultStyle: {
},
});
<强>2。类组件
如果您更喜欢使用类的旧方法,请使用此部分:
// 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 解决方案最适合这种情况。
希望对您有所帮助。
关于javascript - 如何创建自定义文本 - React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53262325/