前言
this.setState
,
全部通過props來渲染也是沒問題的, 不過這種情況不常見。本文所介紹的內容就是通過props和state的定義來談談ReactNative的受控組件和非受控組件。this.setState來控制組件的更新和變化,和iOS原生開發中控制組件變化的思想是有很大區別的,iOS中可以直接設置控件的屬性值。初次接觸
ReactNative中的這種設計思想還是挺難的。非受控組件
<TextInput
/>
在這個最簡單的輸入框組件裏,我們並沒有干涉TextInput中的value展示,即用戶通過鍵盤輸入的內容都會展示在上面,但是不能從其他地方改變其內容。
受控組件
上面提到過,既然通過設置input的value屬性, 無法改變輸入框值,那麼我們把它和state結合在一起,再綁定onChange事件,實時更新value值就行了
constructor(props) {
super(props);
this.state = {
value: "",
}
}
handleChange(e) {
this.setState({
value: e.nativeEvent.text
})
}
render() {
return (
<TextInput
style={styles.style_user_input}
value={this.state.value}
onChange={e => this.handleChange(e)}
/>
);
}
示例
下面展示一個簡單的demo:完整代碼:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
Image,
View,
TextInput,
TouchableOpacity,
} from 'react-native';
class RNTextIput extends Component {
constructor(props) {
super(props);
this.state = {
value: "",
gotText: "",
}
}
handleChange(e) {
this.setState({
value: e.nativeEvent.text
})
}
sendAction() {
this.setState({
gotText: this.state.value
})
}
render() {
return (
<View style={{backgroundColor:'#f4f4f4',flex:1}}>
<TextInput
style={styles.style_user_input}
placeholder='QQ號/手機號/郵箱'
numberOfLines={1}
autoFocus={true}
underlineColorAndroid={'transparent'}
textAlign='center'
value={this.state.value}
onChange={e => this.handleChange(e)}
/>
<TextInput
style={styles.style_pwd_input}
numberOfLines={1}
autoFocus={true}
underlineColorAndroid={'transparent'}
textAlign='center'
value={this.state.gotText}
/>
<View style={{height:1,backgroundColor:'#f4f4f4'}} />
<TouchableOpacity
onPress={() => {
this.sendAction();
}}
>
<View style={styles.style_view_commit} >
<Text style={{color:'#fff'}}>
發送
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.setState({value:this.state.value + "文字~"});
}}
>
<View style={styles.style_view_commit} >
<Text style={{color:'#fff'}}>
手動加入文字
</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
style_image:{
borderRadius:35,
height:70,
width:70,
marginTop:40,
alignSelf:'center',
},
style_user_input:{
backgroundColor:'#fff',
marginTop:100,
height:35,
},
style_pwd_input:{
backgroundColor:'#fff',
height:35,
marginTop:10,
},
style_view_commit:{
marginTop:15,
marginLeft:10,
marginRight:10,
backgroundColor:'#63B8FF',
height:35,
borderRadius:5,
justifyContent: 'center',
alignItems: 'center',
},
});
AppRegistry.registerComponent('RNTextIput', () => RNTextIput);
參考: