Blink是自定义的组件,通过1秒的间隔改变state属性showText值来设置Blink内容的显示,问题是下面代码的preState ,为什么可以直接调用,这个自定义的state名为什么可以直接作为参数来setState。
class Blink extends Component {
constructor(props) {
super(props);
this.state = { showText: false };
setInterval(() => {
this.setState(preState => {
return { showText: !preState.showText };
});
}, 1000);
** 下面是完整代码**
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class Blink extends Component {
constructor(props) {
super(props);
this.state = { showText: false };
setInterval(() => {
this.setState(preState => {
return { showText: !preState.showText };
});
}, 1000);
}
render() {
//三目运算符根据showText的状态来设置显示数据
let display = this.state.showText ? this.props.text : '';
return (
<Text>{display}</Text>
)
}
}
class Test13 extends Component {
render() {
return (
<View>
<Blink text='I am the Blink,which is defined by yourself' />
<Blink text='I am the Blink,which is the system component' />
<Blink text='I am the Blink,view is the parent Component' />
</View>
);
}
}
AppRegistry.registerComponent('Test13', () => Test13);