我正在處理React Native項目,並且我意識到React Native似乎打破了React流(Parent to children)道具更新。React Native不更新子組件道具
基本上,我從一個「App」組件調用一個「Menu」組件,將一個道具傳遞給「Menu」。但是,當我更新「應用程序」狀態時,「菜單」上的道具應該更新,但這不會發生。難道我做錯了什麼?
這是我的代碼:
App.js
import React from 'react';
import {
View,
Text
} from 'react-native';
import Menu from './Menu';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
opacity: 2
}
}
componentDidMount() {
setTimeout(() => {
this.setState({
opacity: 4
});
}, 3000);
}
render() {
return(
<View>
<Menu propOpacity={this.state.opacity} />
</View>
);
}
}
export default App;
Menu.js
import React from 'react';
import {
View,
Text
} from 'react-native';
class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
menuOpacity: props.propOpacity
}
}
render() {
return(
<View>
<Text>Menu opacity: {this.state.menuOpacity}</Text>
</View>
);
}
}
Menu.propTypes = {
propOpacity: React.PropTypes.number
}
Menu.defaultProps = {
propOpacity: 1
}
export default Menu;
不能設置狀態裏面didmount,讓皮斯更新別處。 – Codesingh
@Codesingh yes你可以從'cDM'方法設置狀態。你不能從'render'方法這樣做。 – Andreyco