【发布时间】:2017-05-10 12:39:15
【问题描述】:
我正在做一个 React Native 项目,我意识到 React Native 似乎破坏了 React 流程(父母到孩子)道具更新。
基本上,我从“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 是的,您可以通过
cDM方法设置状态。您不能通过render方法这样做。
标签: reactjs react-native