如何在React中更新父状态?


布偶的表弟派大星丶
2024-12-20 04:20:13 (3月前)

由于道具是不可变的,我不能简单地在组件1中保存它的状态并转发它,对吗?是的,我读过有关redux的内容,但不想使用它。我希望有可能解决它

应对
</跨度>
。我错了吗?

8 条回复
  1. 0# 只怕再见是故人 | 2019-08-31 10-32




    1. this.setState({showChart: true})}
      />



    2. {console.log(this.props)}
    3. Try this example to write inline setState, it avoids creating another function.

    4. </code>

  2. 1# ࿏自ོ༾由ོ༽人͙⃡⌇ | 2019-08-31 10-32



    我发现以下工作解决方案将onClick函数参数从child传递给父组件:




    传递方法的版本()
    </强>




    1. //ChildB component
      class ChildB extends React.Component {

    2. render() {
    3.     var handleToUpdate  =   this.props.handleToUpdate;
    4.     return (<div><button onClick={() => handleToUpdate('someVar')}>
    5.         Push me
    6.       </button>
    7.     </div>)
    8. }
    9. }

    10. //ParentA component
      class ParentA extends React.Component {

    11. constructor(props) {
    12.     super(props);
    13.     var handleToUpdate  = this.handleToUpdate.bind(this);
    14.     var arg1 = '';
    15. }
    16. handleToUpdate(someArg){
    17.         alert('We pass argument from Child to Parent: ' + someArg);
    18.         this.setState({arg1:someArg});
    19. }
    20. render() {
    21.     var handleToUpdate  =   this.handleToUpdate;
    22.     return (<div>
    23.                 <ChildB handleToUpdate = {handleToUpdate.bind(this)} /></div>)
    24. }
    25. }

    26. if(document.querySelector(“#demo”)){
      ReactDOM.render(
      ,
      document.querySelector(“#demo”)
      );
      }

    27. </code>



    看看JSFIDDLE




    传递箭头功能的版本
    </强>




    1. //ChildB component
      class ChildB extends React.Component {

    2. render() {
    3.     var handleToUpdate  =   this.props.handleToUpdate;
    4.     return (<div>
    5.       <button onClick={() => handleToUpdate('someVar')}>
    6.         Push me
    7.       </button>
    8.     </div>)
    9. }
    10. }

    11. //ParentA component
      class ParentA extends React.Component {
      constructor(props) {
      super(props);
      }

    12. handleToUpdate = (someArg) => {
    13.         alert('We pass argument from Child to Parent: ' + someArg);
    14. }
    15. render() {
    16.     return (<div>
    17.         <ChildB handleToUpdate = {this.handleToUpdate} /></div>)
    18. }
    19. }

    20. if(document.querySelector(“#demo”)){
      ReactDOM.render(
      ,
      document.querySelector(“#demo”)
      );
      }

    21. </code>



    看看JSFIDDLE


  3. 2# 日耀九洲 | 2019-08-31 10-32



    我喜欢传递函数的答案,这是一种非常方便的技巧。



    另一方面,您也可以使用pub / sub或使用变体,调度程序来实现此目的

    助焊剂

    确实。理论超级简单,有组件5发送组件3正在监听的消息。组件3然后更新其触发重新渲染的状态。这需要有状态的组件,这取决于您的观点,可能是也可能不是反模式。我个人反对他们,并且宁愿其他东西正在监听调度和更改状态从上到下(Redux这样做,但增加了额外的术语)。




    1. import { Dispatcher } from flux
      import { Component } from React

    2. const dispatcher = new Dispatcher()

    3. // Component 3
      // Some methods, such as constructor, omitted for brevity
      class StatefulParent extends Component {
      state = {
      text: foo
      }

    4. componentDidMount() {
      dispatcher.register( dispatch => {
      if ( dispatch.type === change ) {
      this.setState({ text: bar })
      }
      }
      }

    5. render() {
      return

      { this.state.text }


      }
      }

    6. // Click handler
      const onClick = event => {
      dispatcher.dispatch({
      type: change
      })
      }

    7. // Component 5 in your example
      const StatelessChild = props => {
      return
      }

    8. </code>


    与Flux捆绑的调度程序非常简单,只需注册回调并在发生任何调度时调用它们,通过调度上的内容(在上面的简洁示例中没有)

    payload

    与发送,只是一个消息ID)。如果对您更有意义,您可以非常轻松地将其调整为传统的pub / sub(例如,使用事件中的EventEmitter或其他版本)。


  4. 3# 撩心 | 2019-08-31 10-32



    我找到了以下工作解决方案,通过param将onClick函数参数从child传递给父组件:



    父类:




    1. class Parent extends React.Component {
      constructor(props) {
      super(props)

    2. // Bind the this context to the handler function
    3. this.handler = this.handler.bind(this);
    4. // Set some state
    5. this.state = {
    6.     messageShown: false
    7. };
    8. }

    9. // This method will be sent to the child component
      handler(param1) {
      console.log(param1);
      this.setState({
      messageShown: true
      });
      }

    10. // Render the child component and set the action property with the handler as value
      render() {
      return
      }}

    11. </code>


    儿童班:




    1. class Child extends React.Component {
      render() {
      return (

      {/ The button will execute the handler function set by the parent component /}


      )
      } }

    2. </code>

  5. 4# 圈圈红 | 2019-08-31 10-32



    当你需要在任何级别的孩子与父母之间进行交流时,最好是利用它

    上下文
    </强>
    。在父组件中定义子项可以调用的上下文,例如




    在案例组件3中的父组件中





    1. static childContextTypes = {
      parentMethod: React.PropTypes.func.isRequired
      };

    2.        getChildContext() {
    3.         return {
    4.           parentMethod: (parameter_from_child) => this.parentMethod(parameter_from_child)
    5.         };
    6.       }
    7. parentMethod(parameter_from_child){
      // update the state with parameter_from_child
      }

    8. </code>



    现在在子组件(在您的情况下为组件5),只需告诉它
    要使用其父级上下文的组件。





    1. static contextTypes = {
      parentMethod: React.PropTypes.func.isRequired
      };
      render(){
      return(
      this.context.parentMethod(new_state_value)}
      underlayColor=’gray >

    2.         <Text> update state in parent component </Text>
    3.   </TouchableHighlight>
    4. )}

    5. </code>


    你可以找到Demo项目

    回购


  6. 5# 不想吃东西 | 2019-08-31 10-32



    我想感谢最热烈的回答,让我了解自己的问题基本上是箭头函数的变化和从子组件传递param:




    1. class Parent extends React.Component {
      constructor(props) {
      super(props)
      // without bind, replaced by arrow func below
      }

    2. handler = (val) => {
      this.setState({
      someVar: val
      })
      }

    3. render() {
      return
      }
      }

    4. class Child extends React.Component {
      render() {
      return



    希望它可以帮助某人。


  7. 6# نسر الصحراء | 2019-08-31 10-32


    1. - 我们可以创建ParentComponent并使用handleInputChange方法来更新ParentComponent状态。导入ChildComponent,我们将两个道具从父组件传递给子组件ie.handleInputChange函数和计数。




    1. import React, { Component } from react’;
      import ChildComponent from ‘./ChildComponent’;

    2. class ParentComponent extends Component {
      constructor(props) {
      super(props);
      this.handleInputChange = this.handleInputChange.bind(this);
      this.state = {
      count: ‘’,
      };
      }

    3. handleInputChange(e) {
      const { value, name } = e.target;
      this.setState({ [name]: value });
      }

    4. render() {
      const { count } = this.state;
      return (

      );
      }
      }

    5. </code>




    • 现在我们创建ChildComponent文件并保存为ChildComponent.jsx。此组件是无状态的,因为子组件没有状态。我们使用prop-types库进行道具类型检查。




      1. import React from react’;
        import { func, number } from prop-types’;

      2. const ChildComponent = ({ handleInputChange, count }) => (

        );

      3. ChildComponent.propTypes = {
        count: number,
        handleInputChange: func.isRequired,
        };

      4. ChildComponent.defaultProps = {
        count: 0,
        };

      5. export default ChildComponent;

      6.     </code>
      7.   </pre>
      8. </LI>

登录 后才能参与评论