在React Native中,如何在获得焦点时更改textInput的样式?说我有类似的东西
class MyInput extends Component { render () { return <TextInput style={styles.textInput} />; } }; const stylesObj = { textInput: { height: 50,fontSize: 15,backgroundColor: 'yellow',color: 'black',} }; const styles = StyleSheet.create(stylesObj);
我想将焦点上的背景颜色更改为绿色.
This documentation让我相信解决方案是这样的
class MyInput extends Component { constructor (props) { super(props); this.state = {hasFocus: false}; } render () { return (<TextInput style={this.state.hasFocus ? styles.focusedTextInput : styles.textInput} onFocus={this.setFocus.bind(this,true)} onBlur={this.setFocus.bind(this,false)} />); } setFocus (hasFocus) { this.setState({hasFocus}); } }; const stylesObj = { textInput: { height: 50,} }; const styles = StyleSheet.create({ ...stylesObj,focusedTextInput: { ...stylesObj,backgroundColor: 'green',} });
忽略样式结构中的潜在错误,这会被认为是处理它的正确方法吗?这对我来说似乎非常冗长.
您可以通过传入onFocus和onBlur事件来实现这一点,以便在聚焦和模糊时设置和取消设置样式:
onFocus() { this.setState({ backgroundColor: 'green' }) },onBlur() { this.setState({ backgroundColor: '#ededed' }) },
然后,在TextInput中执行以下操作:
<TextInput onBlur={ () => this.onBlur() } onFocus={ () => this.onFocus() } style={{ height:60,backgroundColor: this.state.backgroundColor,color: this.state.color }} />
我已经建立了一个完整的工作项目here.我希望这有帮助!
https://rnplay.org/apps/hYrKmQ
'use strict'; var React = require('react-native'); var { AppRegistry,StyleSheet,Text,View,TextInput } = React; var SampleApp = React.createClass({ getInitialState() { return { backgroundColor: '#ededed',color: 'white' } },onFocus() { this.setState({ backgroundColor: 'green' }) },render: function() { return ( <View style={styles.container}> <TextInput onBlur={ () => this.onBlur() } onFocus={ () => this.onFocus() } style={{ height:60,color: this.state.color }} /> </View> ); } }); var styles = StyleSheet.create({ container: { flex: 1,marginTop:60 } }); AppRegistry.registerComponent('SampleApp',() => SampleApp);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。