React Native ref高级用法&&setNativeProps使用
ref属性不只是string http://blog.csdn.NET/que_li/article/details/52872479 callback。这一特性让开发者对ref的使用更加灵活。
render() {
return <TextInput ref={(c) => this._input = c} />;
},componentDidMount() {
this._input.focus();
},
render(){
return <View ref={ (e) => this._view = e } />//将组件view作为参数赋值给了this._view
}
componentDidMount(){
this._view.style = { backgroundColor:'red',width:100,0);">height:200 }
}
需要提醒大家的是,只有在组件的render方法被调用时,ref才会被调用,组件才会返回ref。如果你在调用this.refs.xx时render方法还没被调用,那么你得到的是undefined。 让组件做到局部刷新setNativeProps import React,{
AppRegistry,Component,StyleSheet,Text,View,TextInput
} from 'react-native';
class AwesomeProject extends Component {
// 构造
constructor(props) {
super(props);
// 初始状态
this.state = {
textInputValue: ''
};
this.buttonPressed = this.buttonPressed.bind(this);
}
buttonPressed() { //当按钮按下的时候执行此函数
let textInputValue = 'new value';
this.setState({textInputValue});
//修改文本输入框的属性值
this.refs.textInputRefer.setNativeProps({
editable:false
});
this.refs.text2.setNativeProps({
style:{
color:'blue',fontSize:30
}
});
//使文本输入框变为不可编辑
}
render() {
return (
//ref={'text2'}> //指定本组件的引用名
<View style={styles.container}>
<Text style={styles.buttonStyle} onPress={this.buttonPressed}>
按我
</Text>
<Text style={styles.textPromptStyle} ref="text2">
文字提示
</Text>
<View>
<TextInput style={styles.textInputStyle}
ref="textInputRefer"
value={this.state.textInputValue}
onChangeText={(textInputValue)=>this.setState({textInputValue})}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,justifyContent: 'center',alignItems: 'center'
},buttonStyle: { //文本组件样式,定义简单的按钮
fontSize: 20,backgroundColor: 'grey'
},textPromptStyle: { //文本组件样式
fontSize: 20
},textInputStyle: { //文本输入组件样式
width: 150,height: 50,fontSize: 'grey'
}
});
AppRegistry.registerComponent('Redux',() => AwesomeProject);
当点击按钮时,会刷新3个控件的值,但是只是单独去改变,而不是通过改变state状态机的机制来刷新界面,在重复需要多次刷新时使用,普通的时候直接通过state改变即可。 这样用的缺点就是局部改变,回导致状态机混乱。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |