ReactJS: setState on parent inside child component

后端 未结 7 1287
孤街浪徒
孤街浪徒 2020-12-02 10:18

What is the recommended pattern for doing a setState on a parent from a child component.

var Todos = React.createClass({
  getInitialState: function() {
             


        
7条回答
  •  囚心锁ツ
    2020-12-02 11:03

    For those who are maintaining state with the React Hook useState, I adapted the above suggestions to make a demo slider App below. In the demo app, the child slider component maintains the parent's state.

    The demo also uses useEffect hook. (and less importantly, useRef hook)

    import React, { useState, useEffect, useCallback, useRef } from "react";
    
    //the parent react component
    function Parent() {
    
      // the parentState will be set by its child slider component
      const [parentState, setParentState] = useState(0);
    
      // make wrapper function to give child
      const wrapperSetParentState = useCallback(val => {
        setParentState(val);
      }, [setParentState]);
    
      return (
        
    Parent State: {parentState}
    ); }; //the child react component function Child({parentStateSetter}) { const childRef = useRef(); const [childState, setChildState] = useState(0); useEffect(() => { parentStateSetter(childState); }, [parentStateSetter, childState]); const onSliderChangeHandler = e => { //pass slider's event value to child's state setChildState(e.target.value); }; return (
    ); }; export default Parent;

提交回复
热议问题