我想setState
從A
組件到B
組件。 A
和B
是不同的JS文件。我試圖導入B
到A
並訪問B
中的功能。還有使B
中的函數靜態化,然後只查找靜態函數沒有實例,所以我無法在靜態中訪問this
。React Native - 不同JS文件之間的setState
A.js
import B from '../B';
class A extends React.Component {
ChangeBContent(){
B.SetContent();
}
render(){
return(
<View>
<SpeicalBtn onPress={()=> this.ChangeBContent()}/>
</View>
);
}
}
module.exports = A;
AppRegistry.registerComponent('myApp',() => A);
B.js
class B extends React.Component {
constructor(props) {
super(props);
this.state = {
content:''
}
}
SetContent(){
this.setState({content:'123'});
}
render(){
return(
<View>
<Text>{this.state.content}</Text>
</View>
);
}
}
module.exports = B;
AppRegistry.registerComponent('myApp',() => B);
你正在嘗試調用一個靜態方法B.SetContent();而應該找到一種方法來獲取'B'的實例並通過實例調用該方法。 – Panther