在上一篇文章“布局和Flexbox"中,我们讨论了Flexbox及其属性。在本教程中,我们将使用Flex设置元素的位置。
创建一个View组件,并放置两个元素TextInput和Button。具有flex属性(1)的View组件占据了设备的全部空间。元素TextInput和Button在默认的flex axis轴中设置(作为列)。
import React, { Component } from "react"; import { StyleSheet, TextInput, View , Button } from "react-native"; export default class App extends Component { state = { placeName: "", places: [] }; placeNameChangedHandler = val => { this.setState({ placeName: val }); }; placeSubmitHandler = () => { alert("button clicked") }; render() { return ( <View style={styles.container}> <TextInput placeholder="An awesome place" onChangeText={this.placeNameChangedHandler} style={styles.placeInput} /> <Button title="Button" onPress={this.placeSubmitHandler} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 26, backgroundColor: "#fff", justifyContent: "flex-start" } });
输出:
在此示例中,我们将Button置于TextInput元素的右侧。在具有flex:1和flexDirtection:"row"的父视图内添加一个子View组件。设置flex:1(用于内部View)从上到下以及从左到右占据整个空间。 flexDirtection:"row"在内部View组件内部按行设置元素。
import React, { Component } from "react"; import { StyleSheet, View, TextInput, Button } from "react-native"; export default class App extends Component { state = { placeName: "", places: [] }; placeNameChangedHandler = val => { this.setState({ placeName: val }); }; placeSubmitHandler = () => { alert("button clicked") }; render() { return ( <View style={styles.container}> <View style={styles.innerContainer}> <TextInput placeholder="An awesome place" onChangeText={this.placeNameChangedHandler} /> <Button title="Button" onPress={this.placeSubmitHandler} /> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 26, backgroundColor: "#fff", justifyContent: "flex-start" }, innerContainer:{ flex: 1, flexDirection: "row" } });
输出:
在此示例中,我们删除了内部View的flex属性,并添加了宽度:100%。移除flex表单内部View会设置元素的默认尺寸。内部视图的设置宽度:"100%"占据元素的全宽和默认高度。
import React, { Component } from "react"; import { StyleSheet, View, TextInput, Button } from "react-native"; export default class App extends Component { state = { placeName: "", places: [] }; placeNameChangedHandler = val => { this.setState({ placeName: val }); }; placeSubmitHandler = () => { alert("button clicked") }; render() { return ( <View style={styles.container}> <View style={styles.innerContainer}> <TextInput placeholder="An awesome place" onChangeText={this.placeNameChangedHandler} style={styles.textStyle} /> <Button title="Button" onPress={this.placeSubmitHandler} /> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 26, backgroundColor: "#fff", justifyContent: "flex-start" }, innerContainer:{ //flex: 1, width: "100%", flexDirection: "row", justifyContent: "space-between", alignItems: "center" }, textStyle:{ width: "70%", backgroundColor: "gray", }, buttonStyle:{ width: "30%", } });
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)