简体   繁体   English

从子组件更新父组件

[英]Updating parent component from child component

I can't rerender the parent component from the child component - I pass componentDidMount as props to child class, then I call it there, and expect the parent to rerender. 我无法从子组件中重新渲染父组件-我将componentDidMount作为props传递给子类,然后在此处调用它,并期望父组件重新渲染。 The render function is called, but the content remains unchanged. 调用了render函数,但是内容保持不变。 What's wrong? 怎么了?

var Parent = React.createClass({
   getInitialState: function () { return {content: 'clean'}; },
   componentDidMount: function () {
      this.setState({content: 'changed!'});
   },
   render: function () {
      return React.createElement('div', {rerender: this.componentDidMount.bind(this)}, this.state.content);
   }
});

var Child = React.createClass({
   render: function () {
      return React.createElement('div', {onClick: this.handleClick}, 'click me');
   },
   handleClick: function () {
      this.props.rerender();
   }
});

ReactDOM.render(
        React.createElement(ReactRouter.Router, {history: ReactRouter.browserHistory},
                React.createElement(ReactRouter.Route, {path: '/parent', component: Parent})
        )
, document.getElementById('content'));

componentDidMount() is a lifecycle function called when the component has completed rendering. componentDidMount()是组件完成渲染后调用的生命周期函数。

Calling it is seeming like you are circumventing the entire rerendering process. 调用它似乎在绕过整个重新渲染过程。

You should instead create your own function. 您应该改为创建自己的函数。

   changeContent: function () {
      this.setState({content: 'changed!'});
   },

And then pass changeContent() to rerender . 然后将changeContent()传递给rerender

Generally, avoid passing React's LifeCycle methods around! 通常,避免传递React的LifeCycle方法!

To tackle all this kind of things, the guys at Facebook come up with unidirectional data flow pattern. 为了解决所有此类问题,Facebook的人员提出了单向数据流模式。 Your child component should not know about the parent but rather it should change some sort of state (Flux, Redux, Reflux). 您的子组件不应该知道父组件,而应该更改某种状态(Flux,Redux,Reflux)。 Changes to the state will trigger rerendering of the parent component. 状态更改将触发父组件的重新呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM