How to update the Context value in Provider from the Consumer

后端 未结 5 862
日久生厌
日久生厌 2020-12-09 01:08

MyContext.js

import React from \"react\";

const MyContext = React.createContext(\'test\');
export default MyContext;

Cre

5条回答
  •  天命终不由人
    2020-12-09 02:03

    Firstly, in order to update the context from the consumer, you need to access the context outside of the render function, For details on how to do this, check

    Access React Context outside of render function

    Secondly, you should provide a handler from Provider which updates the context value and not mutate it directly. Your code will look like

    Parent.js

    import MyContext from "./MyContext.js";
    import Child from "./Child.js";
    
    class Parent extends Component {
    
        constructor(props) {
          super(props);
          this.state = {
            Message: "Welcome React",
            ReturnMessage:""
          };
        }
    
        updateValue = (key, val) => {
           this.setState({[key]: val});
        }
        render() {
            return (
                     
                   
               
           )
        }
    }
    

    Child

    import MyContext from "./MyContext.js";
    
    class Child extends Component {
    
        constructor(props) {
          super(props);
          this.state = {        
            ReturnMessage:""
          };
        }
    
        ClearData(e){
            const val = e.target.value;
            this.setState({
               ReturnMessage:val
            });
            this.props.context.updateValue('ReturnMessage', val);
        }
    
        render() {
            return (
               
                 

    {this.props.context.state.Message}

    }
    ) } } const withContext = (Component) => { return (props) => { {(context) => { return }} } } export default withContext(Child);

提交回复
热议问题