我试图在我的 TextInput
上放置一个 Avatar
元素,这样它看起来就像一个传统的搜索栏,但它不会超过 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 guide .
关于javascript - 将元素放在文本框上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51288420/