我想通过运行功能来编辑其他componenet的状态,该功能检查应用程序的当前状态是否处于活动状态,这意味着该应用程序每次运行时都会运行。
let d = new Date().getHours();
let title = messages[`_${d}`].message;
function getAppState() {
AppState.addEventListener("change", (state) => {
if(state == "active") {
d = new Date().getHours();
title = messages[`_${d}`].message;
// App.setState({ text: title }); **Not working!
console.log(title);
}
});
}
export default class App extends React.Component {
constructor() {
super();
this.state = { text: title };
getAppState();
}
render() {
return (
<View>
<StatusBar hidden={ true } />
<Text style={styles.title}>{title}</Text>
</View>
);
}
}
我想根据小时更改文本的值。
答案 0 :(得分:0)
我没有测试环境,但我会这样做:
export default class App extends React.Component {
constructor() {
super();
this.state = {
text: title
};
// Bind updateTile() so `this` corresponds tho the react component and things
// like `this.setState()` are available. Otherwise `this` would be `AppState`
this.updateTitle = this.updateHour.bind(this);
}
componentWillMount() {
// Listen for the event
AppState.addEventListener("change", this.updateTitle);
}
updateTitle(state) {
if (state == "active") {
const d = new Date().getHours();
const title = messages[`_${d}`].message;
this.setState({
text: title
});
console.log(title);
}
}
render() {
return (
<View >
<StatusBar hidden={true} />
<Text style = {styles.title}>{title}</Text>
</View >
);
}
}
如果您希望updateTitle()
成为另一个功能并且不属于Component
的一部分,我会这样做:
const updateComponentTitle = state => {
if (state == "active") {
const d = new Date().getHours();
const title = messages[`_${d}`].message;
this.setState({
text: title
});
console.log(title);
}
}
export default class App extends React.Component {
constructor() {
super();
this.state = {
text: title
};
// Bind updateTile() so `this` corresponds tho the react component and things
// like `this.setState()` are available. Otherwise `this` would be `AppState`
this.updateTitle = udpateComponentTitle.bind(this);
}
componentWillMount() {
// Listen for the event
AppState.addEventListener("change", this.updateTitle);
}
render() {
return (
<View >
<StatusBar hidden={true} />
<Text style = {styles.title}>{title}</Text>
</View >
);
}
}