Javascript React Native-编辑其他组件';s州
我想通过运行函数来编辑其他组件的状态,该函数检查应用程序的当前状态是否处于活动状态,这意味着每次应用程序进入前一轮时它都会运行Javascript React Native-编辑其他组件';s州,javascript,react-native,Javascript,React Native,我想通过运行函数来编辑其他组件的状态,该函数检查应用程序的当前状态是否处于活动状态,这意味着每次应用程序进入前一轮时它都会运行 let d = new Date().getHours(); let title = messages[`_${d}`].message; function getAppState() { AppState.addEventListener("change", (state) => { if(state == "active") { d
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>
);
}
}
设d=newdate().getHours();
让title=messages[`{d}`].message;
函数getAppState(){
AppState.addEventListener(“更改”,(状态)=>{
如果(状态=“活动”){
d=新日期().getHours();
title=消息[`{d}`];
//App.setState({text:title});**不工作!
控制台日志(标题);
}
});
}
导出默认类App扩展React.Component{
构造函数(){
超级();
this.state={text:title};
getAppState();
}
render(){
返回(
{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 = 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 >
);
}
}
}
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 >
);
}