在最新的 5.0 预发行版中,有一个更简洁的解决方案。使用带有钩子的全新contentWidth
道具useWindowDimensions
,图像将自动缩放到内容宽度!
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,
},
});
结果: