首页 > 解决方案 > 将元素放在文本框上

问题描述

我正在尝试Avatar在我的上方放置一个元素TextInput,使其看起来像一个传统的搜索栏,但它不会越过TextInput请它是否工作,或者是否可以使用另一种更好的方法将搜索图标放在TextInput建议的上方,谢谢

 import { Avatar } from 'react-native-elements';
import FontAwesome
from './node_modules/@expo/vector-icons/fonts/FontAwesome.ttf';
import MaterialIcons
from './node_modules/@expo/vector-icons/fonts/MaterialIcons.ttf';


export default class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {timePassed: false};
}
   state = {
    fontLoaded: false
    };
   async componentWillMount() {
    try {
        await Font.loadAsync({
            FontAwesome,
            MaterialIcons
        });
        this.setState({ fontLoaded: true });
    } catch (error) {
        console.log('error loading icon fonts', error);
    }
 }

 render() {
    setTimeout(() => {
        this.setState({timePassed: true})
    }, 4000);
    if (!this.state.timePassed) {
        return <Splash/>;
    } else {
        return (
            <View style={BackStyles.container}>
                <Avatar style={BackStyles.searchIcon} icon={{ name: 'search', size: 25, }}/>
                <TextInput placeholder="Search for your herbs.."
                underlineColorAndroid={'transparent'}  style={BackStyles.textBox}
            /></View>
        );
    }
}
}

const BackStyles = StyleSheet.create({
container: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    alignSelf: 'stretch',
    flex: 1,
    backgroundColor: '#E2E2E2',
    marginTop: 20,
  //  width: '100%'
},
textBox: {
    flex: 1,
    height: 45,
    padding: 4,
  //  textAlignVertical: 'top',
    paddingLeft: 20,
   // marginRight: 5,
    flexGrow: 1,
  //  fontSize: 18,
    color: '#000',
    backgroundColor: '#fff',
   // textAlign: 'center'
},
searchIcon:{
    position: 'absolute',
    alignSelf: 'stretch',
    height: 45,
    flex: 1,
    top: 50,
    flexGrow: 1,
    padding: 4
}
});

标签: javascriptcssreactjsreact-native

解决方案


您可以使用 Flexbox 的justifyContent功能将搜索图标强制TextInput在左侧,将搜索图标强制在右侧。如果您在容器上而不是在容器上添加边框TextInput,则整个内容将显示为固定在右侧的搜索图标TextInput,而实际上它们是两个独立的组件。

// styles
const styles = StyleSheet.create({
  searchBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: 'black',
  },
});

// the component
<View style={styles.searchBox}>
  <TextInput ...yourprops />
  <Avatar ...yourprops />
</View>

如果你想了解更多关于justifyContentFlexbox 以及它是多么神圣的信息,你应该查看 Chris Coyier 的Flexbox 指南


推荐阅读