我正在研究一个React Native项目,我意识到React Native似乎打破了React流(Parent to children)道具更新。
基本上,我从“App”组件调用“Menu”组件,将prop传递给“Menu”。但是,当我更新“App”状态时,“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;
答案 0 :(得分:1)
React没有破坏数据流......你是。在初始状态初始化之后,当父级发送更新的道具时,您忘记更新菜单的状态。
试试这个......
class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
menuOpacity: props.propOpacity
}
}
componentWillUpdate(nextProps, nextState) {
nextState.menuOpacity = nextProps.propOpacity;
}
render() {
return(
<View>
<Text>Menu opacity: {this.state.menuOpacity}</Text>
</View>
);
}
}