如何在React Native中以16:9的比例查看样式?

时间:2015-04-04 13:51:57

标签: ios facebook reactjs flexbox react-native

我想让红色视图保持16:9的比例。我尝试但失败了。我知道React Native使用Flexbox(在Javascript中重新实现),但我不知道如何做到这一点。感谢。

这是我的Javascript:

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  View,
} = React;

var AwesomeProject = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <View style={styles.banner}>

        </View>
        <View style={styles.items}>

        </View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  banner: {
    backgroundColor: 'red',
    flex: 1,
  },
  items: {
    backgroundColor: 'blue',
    flex: 3,
  },
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

以下是React Native中的Flexbox文档:

http://facebook.github.io/react-native/docs/flexbox.html#content

这是有效的风格道具:

Valid style props: [
  "width",
  "height",
  "top",
  "left",
  "right",
  "bottom",
  "margin",
  "marginVertical",
  "marginHorizontal",
  "marginTop",
  "marginBottom",
  "marginLeft",
  "marginRight",
  "borderWidth",
  "borderTopWidth",
  "borderRightWidth",
  "borderBottomWidth",
  "borderLeftWidth",
  "position",
  "flexDirection",
  "flexWrap",
  "justifyContent",
  "alignItems",
  "alignSelf",
  "flex",
  "resizeMode",
  "backgroundColor",
  "borderColor",
  "borderRadius",
  "tintColor",
  "opacity",
  "fontFamily",
  "fontSize",
  "fontWeight",
  "fontStyle",
  "lineHeight",
  "color",
  "containerBackgroundColor",
  "textAlign",
  "writingDirection",
  "padding",
  "paddingVertical",
  "paddingHorizontal",
  "paddingTop",
  "paddingBottom",
  "paddingLeft",
  "paddingRight",
  "borderTopColor",
  "borderRightColor",
  "borderBottomColor",
  "borderLeftColor",
  "overflow",
  "shadowColor",
  "shadowOffset",
  "shadowOpacity",
  "shadowRadius",
  "transformMatrix",
  "rotation",
  "scaleX",
  "scaleY",
  "translateX",
  "translateY"
]"

2 个答案:

答案 0 :(得分:4)

React Native(自0.40起)支持aspectRatio道具。

你可以这样做:

style={{ aspectRatio: 16/9 }}

请参阅Maintain aspect ratio of image with full width in React Native

答案 1 :(得分:0)

您可以使用on布局功能。

    class AwesomeProject = extends React.Component<{}> {

    constructor(props) {
            super(props)
            this.state = {width: 0,height:0}
        }

        onPageLayout = (event) => {
            const {width, height} = event.nativeEvent.layout;
            this.setState({
                width,
                height
            })
        };

          render(){
            return (
              <View style={styles.container}>
                <View style={[
styles.banner,
{
height:this.state.width*9/16
}
]}>

                </View>
                <View style={styles.items}>

                </View>
              </View>
            );
          }
        });