反应原生的TextInput焦点样式
发布时间:2020-12-15 20:41:30 所属栏目:百科 来源:网络整理
导读:在React Native中,如何在获得焦点时更改textInput的样式?说我有类似的东西 class MyInput extends Component { render () { return TextInput style={styles.textInput} /; }};const stylesObj = { textInput: { height: 50,fontSize: 15,backgroundColor:
在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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |