这是我找到的最干净的解决方案。56.25%为315/560(宽/高),这是固有比。
const html =
'<html><body><meta name="viewport" content="device-width, initial-scale=1,maximum-scale=1.0, user-scalable=1.0">' +
'<div style="display: flex; justify-content: center; align-items: center; height: 100%"><div style="position: relative; width: 100%; height: 0; padding-bottom: 56.25%;">' +
`<iframe width="560" height="315" src="${url}" frameborder="0" style="position:absolute; width: 100%; height: 100%; left: 0; top: 0" allow="autoplay; encrypted-media" allowfullscreen></iframe>` +
'</div></div>' +
'</body></html>';
return <WebView style={{ flex: 1 }} source={{ html }} />;
要获得显示YouTube视频的完整解决方案,可以执行以下操作:
import * as React from 'react';
import { AppState, WebView } from 'react-native';
import { Container, Header, Title, Content, Button, Right, Body, Left, Icon } from 'native-base';
import styles from '../services/Styles';
export default class extends React.Component {
state = {
appState: AppState.currentState,
};
componentDidMount() {
AppState.addEventListener('change', this._handleStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleStateChange);
}
_handleStateChange = nextAppState =>
this.setState({
appState: nextAppState,
});
render() {
const { params: { url, label, isYouTube } } = this.props.navigation.state;
const { appState } = this.state;
if (isYouTube) {
// YouTube videos will play in the background on some devices if
// we do not destroy the WebView when the app goes into the
// background.
// This is required to comply with YouTube policies and to
// be accepted into the Google Play store.
if (appState !== 'active') return null;
// Create an intrinsic ratio for videos using this technique:
// https://alistapart.com/article/creating-intrinsic-ratios-for-video
const html =
'<html><body><meta name="viewport" content="device-width, initial-scale=1,maximum-scale=1.0, user-scalable=1.0">' +
'<div style="display: flex; justify-content: center; align-items: center; height: 100%"><div style="position: relative; width: 100%; height: 0; padding-bottom: 56.25%;">' +
`<iframe width="560" height="315" src="${url}" frameborder="0" style="position:absolute; width: 100%; height: 100%; left: 0; top: 0" allow="autoplay; encrypted-media" allowfullscreen></iframe>` +
'</div></div>' +
'</body></html>';
return <WebView style={{ flex: 1 }} source={{ html }} />;
}
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => this.props.navigation.goBack()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body style={{ flex: 2 }}>
<Title>{label}</Title>
</Body>
</Header>
<Content contentContainerStyle={{ flex: 1 }}>
<WebView style={{ flex: 1 }} source={{ uri: url }} />
</Content>
</Container>
);
}
}