在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);