React native 向扩展的本机组件应用样式的推荐方法是什么?
我已经扩展了该组件,以便有一个具有自定义字体的可重用文本组件 我的自定义组件应该接受传递给它的样式,并向其中添加自定义字体 我目前正在这样做: MyText.jsReact native 向扩展的本机组件应用样式的推荐方法是什么?,react-native,React Native,我已经扩展了该组件,以便有一个具有自定义字体的可重用文本组件 我的自定义组件应该接受传递给它的样式,并向其中添加自定义字体 我目前正在这样做: MyText.js import React from 'react' import { Text, StyleSheet } from 'react-native'; export default class MyText extends React.Component { render() { cons
import React from 'react'
import {
Text,
StyleSheet
} from 'react-native';
export default class MyText extends React.Component {
render() {
const style =
Object.assign( {},
StyleSheet.flatten(this.props.style),
{fontFamily: "My Font"}
);
return (
<Text style={style}>
{this.props.children}
</Text>
);
}
}
从“React”导入React
进口{
文本,
样式表
}从“反应本机”;
导出默认类MyText扩展React.Component{
render(){
常量样式=
赋值({},
样式表.flatte(this.props.style),
{fontFamily:“我的字体”}
);
返回(
{this.props.children}
);
}
}
虽然这样做可以像预期的那样工作,但每次都要扁平化样式表似乎是错误的。上面是一个简单的例子,我可以想到我可以使用此模式的其他组件。出于这个原因,我想确保我没有忽略一个更合适的方法。这取决于您想要定制多少。在这种情况下,如果它只是一种不同的字体,它可能是
import React from 'react'
import {
Text,
StyleSheet
} from 'react-native';
import _ from 'lodash';
export default class MyText extends React.Component {
render() {
const filteredProps = _.omit(this.props, 'style');
return (
<Text style={[{fontFamily: "My Font"}, this.props.style]} {...filteredProps} />
);
}
}
从“React”导入React
进口{
文本,
样式表
}从“反应本机”;
从“lodash”进口;
导出默认类MyText扩展React.Component{
render(){
const filteredrops=u.omit(this.props,'style');
返回(
);
}
}
您可以为组件提供一系列样式。因此,在您的情况下,以下操作将起作用:''如果不希望将customStyle作为数组的第一项,则customStyle将覆盖style对象上的现有键。