在React Native中以编程方式设置卡的高度



在我的React Native应用程序中,我想使用简单的<View>来显示卡片,该卡片将有一个设定的高度开始并显示两行文本。

如果文本长于两行;更多";按钮,单击时将扩展视图的高度以适应所有文本。

我的问题是如何确定/计算高度?

我正在考虑的方法是使用两个不同的样式类并以编程方式切换它们,但我不确定如何动态计算<View>的高度,以便所有文本都能放入其中,无论它有多长

const cardStyle = this.props.moreButtonClicked ? "card-long" : "card-std";
return (
<View style={cardStyle}>
<Text>
{
this.props.cardContent.length <= 120
? this.props.cardContent
: this.props.moreButtonClicked
? this.props.cardContent
: this.props.cardContent.substring(0, 119)
}
</Text>
</View>
);

具体来说,我如何计算出card-long风格类的正确高度?或者有更好的方法来处理这个问题吗?谢谢

您可以在使用此库渲染文本之前确定文本高度:https://github.com/aMarCruz/react-native-text-size

这里有一个例子:

import rnTextSize, { TSFontSpecs } from 'react-native-text-size'
type Props = {}
type State = { width: number, height: number }
// On iOS 9+ will show 'San Francisco' and 'Roboto' on Android
const fontSpecs: TSFontSpecs = {
fontFamily = undefined,
fontSize = 24,
fontStyle = 'italic',
fontWeight = 'bold',
}
const text = 'I ❤️ rnTextSize'
class Test extends Component<Props, State> {
state = {
width: 0,
height: 0,
}
async componentDidMount() {
const width = Dimensions.get('window').width * 0.8
const size = await rnTextSize.measure({
text,             // text to measure, can include symbols
width,            // max-width of the "virtual" container
...fontSpecs,     // RN font specification
})
this.setState({
width: size.width,
height: size.height
})
}
// The result is reversible
render() {
const { width, height } = this.state
return (
<View style={{ padding: 12 }}>
<Text style={{ width, height, ...fontSpecs }}>
{text}
</Text>
</View>
)
}
}

最新更新