【发布时间】:2018-05-16 13:16:41
【问题描述】:
我有一个 React 组件 MoviesGallery.js,配置如下:
class MoviesGallery extends Component {
constructor(props) {
super(props)
this.state = { currentImage: 0 };
this.closeLightbox = this.closeLightbox.bind(this);
this.openLightbox = this.openLightbox.bind(this);
this.gotoNext = this.gotoNext.bind(this);
this.gotoPrevious = this.gotoPrevious.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({movies_genre: nextProps.movies_genre})
}
我已经在我的主 App.js 文件中渲染了组件,如下所示:
class App extends Component {
render() {
return (
<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
<RaisedButton primary={true} label="Query" className="header_buttons"/>
<RaisedButton secondary={true} label="Reset" className="header_buttons"/>
</header>
<MoviesGallery/>
</div>
</MuiThemeProvider>
);
}
}
我想在不重新创建组件的情况下更新我的 MoviesGallery 组件的道具。由于我已经将 componentWillReceiveProps() 添加到 MoviesGallery 组件,我该如何做到这一点,当单击“查询”按钮时,它会将新道具传递给 已经渲染 MoviesGallery 和 componentWillReceiveProps() 应该会导致它重新渲染,因为状态会改变。
只是对单击渲染的 MoviesGallery 组件时会更改道具本身的功能感到困惑。
提前致谢!
【问题讨论】:
-
没有办法改变道具除非你用新的道具重新渲染它 - 你不能改变道具。当组件被重新渲染时,
componentWillReceiveProps被调用。 -
如何在按钮单击时使用新道具重新渲染它?
-
你没有发布
MoviesGallery的渲染方法,但是当你只使用渲染内部的道具时,不需要设置本地状态。当一个组件收到一个新的 prop 时,它会用新的 prop 再次调用 render。 -
@HasanJafri 在你的父母那里做。接受
MovieGallery中的单击处理程序道具并将事件处理程序传递给它。然后,在事件处理程序中,在您的父级中设置状态,以便在单击按钮时设置父级的状态。该状态可以是您要传递给MovieGallery的新道具。
标签: javascript reactjs