我有一个具有以下配置的 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 组件的 props,而不需要重新创建该组件。由于我已经将 componentWillReceiveProps() 添加到 MoviesGallery 组件中,因此当单击“查询”按钮时,如何才能将新的 Prop 传递给已渲染 MoviesGallery 和 componentWillReceiveProps() 应该导致它由于状态会改变而重新渲染。
只是对单击渲染的 MoviesGallery 组件时会更改 Prop 本身的功能感到困惑。
提前致谢!
最佳答案
当父组件将新的(值) Prop 传递给子组件时,子组件将自动调用 render 方法。无需在子组件内设置本地状态来“存储”新 Prop 。
这是一个 Counter
的小示例,它接收 count
属性并仅显示它,而在这种情况下,父 App
将更改其状态中的值并将新值传递给 Counter
:
class Counter extends React.Component {
render() {
const { count } = this.props;
return (
<div>{count}</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
}
onClick = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
const { count } = this.state;
return (
<div>
<Counter count={count} />
<button onClick={this.onClick}>Add to counter</button>
</div>);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - 如何从 App.js 更新渲染的 React 组件的 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47610234/