在React Native中,textInput
当你获得焦点时,你如何改变它的风格?说我有类似的东西
class MyInput extends Component { render () { return; } }; const stylesObj = { textInput: { height: 50, fontSize: 15, backgroundColor: 'yellow', color: 'black', } }; const styles = StyleSheet.create(stylesObj);
我想改变焦点的背景颜色green
.
这篇文档让我相信解决方案是这样的
class MyInput extends Component { constructor (props) { super(props); this.state = {hasFocus: false}; } render () { return (); } setFocus (hasFocus) { this.setState({hasFocus}); } }; const stylesObj = { textInput: { height: 50, fontSize: 15, backgroundColor: 'yellow', color: 'black', } }; const styles = StyleSheet.create({ ...stylesObj, focusedTextInput: { ...stylesObj, backgroundColor: 'green', } });
忽略样式结构中的潜在错误,这会被认为是处理它的正确方法吗?这对我来说似乎非常冗长.
您可以通过传入onFocus和onBlur事件来实现这一点,以便在聚焦和模糊时设置和取消设置样式:
onFocus() { this.setState({ backgroundColor: 'green' }) }, onBlur() { this.setState({ backgroundColor: '#ededed' }) },
然后,在TextInput中执行以下操作:
this.onBlur() } onFocus={ () => this.onFocus() } style={{ height:60, backgroundColor: this.state.backgroundColor, color: this.state.color }} />
我已经建立了一个完整的工作项目在这里.我希望这有帮助!
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' }) }, onBlur() { this.setState({ backgroundColor: '#ededed' }) }, render: function() { return (); } }); var styles = StyleSheet.create({ container: { flex: 1, marginTop:60 } }); AppRegistry.registerComponent('SampleApp', () => SampleApp); this.onBlur() } onFocus={ () => this.onFocus() } style={{ height:60, backgroundColor: this.state.backgroundColor, color: this.state.color }} />