在开发React Native Apps时,我使用react-native-render-html将字符串转换为html元素。我从后台收到了RESTful API发来的字符串,在<img>
标签中已经设置了宽和高:
<img class="aligncenter" src="https://www.allfin.com/u/cms/www/201811/13142949sf02.jpg" width="600" height="408" />
但我希望将图像调整到窗口的最大宽度,因此我使用:
imagesMaxWidth={Dimensions.get('window').width}
整个片段如下:
<ScrollView style={styles.content}>
<Text style={styles.title}>{this.props.title}</Text>
<Text>{this.props.date}</Text>
<HTML
html={this.props.content}
imagesMaxWidth={Dimensions.get('window').width - 40}
/>
</ScrollView>
但是图像不能调整到窗口的最大宽度。
那么我该如何设置它呢?
谢谢
发布于 2020-02-19 20:46:40
使用ignoredStyles
属性忽略原始图片的宽度和高度。使用ignoredStyles={['height', 'width']}
解决此问题。
发布于 2020-09-26 19:28:29
在最新的5.0预发布版本中,有了一个更干净的解决方案。使用全新的带有useWindowDimensions
钩子的contentWidth
道具,图像将自动缩放到内容宽度!
yarn add react-native-render-html@unstable
import * as React from 'react';
import {ScrollView, StyleSheet, useWindowDimensions} from 'react-native';
import HTML from 'react-native-render-html';
const html = `
<img class="aligncenter" src="https://www.allfin.com/u/cms/www/201811/13142949sf02.jpg" width="600" height="408" />
`;
export default function App() {
const {width} = useWindowDimensions();
return (
<ScrollView contentContainerStyle={styles.container}>
<HTML contentWidth={width} html={html} />
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
flexGrow: 1,
},
});
结果:
此外,如果您想要此行为,并且不希望图像大于300,则可以使用新的computeEmbeddedMaxWidth
属性:
import * as React from 'react';
import {ScrollView, StyleSheet, useWindowDimensions} from 'react-native';
import HTML from 'react-native-render-html';
const html = `
<img class="aligncenter" src="https://www.allfin.com/u/cms/www/201811/13142949sf02.jpg" width="600" height="408" />
`;
function computeEmbeddedMaxWidth(contentWidth, tagName) {
if (tagName === 'img') {
return Math.min(contentWidth, 300);
}
return contentWidth;
}
export default function App() {
const {width} = useWindowDimensions();
return (
<ScrollView contentContainerStyle={styles.container}>
<HTML
contentWidth={width}
computeImagesMaxWidth={computeImagesMaxWidth}
html={html}
/>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
flexGrow: 1,
},
});
结果:
https://stackoverflow.com/questions/60298837
复制相似问题