javascript - 将元素放在文本框上
问题描述
我正在尝试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
}
});
解决方案
您可以使用 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>
如果你想了解更多关于justifyContent
Flexbox 以及它是多么神圣的信息,你应该查看 Chris Coyier 的Flexbox 指南。
推荐阅读
- flutter - Flutter中初始化页面和singleItem = true时如何选择默认项(itemTag)?
- java - 无法编组 EJB 参数?
- javascript - 如何使用 Jquery 或纯 JavaScript 更改 URL 参数名称?
- java - 为接口创建 Bean
- asp.net-core - 将 PetaPoco v6 与 asp.NET 核心集成
- user-input - 类型保护 React.KeyboardEvent 以重用事件处理程序
- docker - “docker ps -a”未列出的“docker container prune”删除的额外容器是什么?
- java - onCreate() 方法不是调用方法 A 而是 onStart() 调用方法 A
- html - 带有自定义播放按钮的视频上的文字
- reactjs - 如何更改 Material-UI 自动完成列表的样式?