简体   繁体   中英

Child component props are empty though they're passed from a parent component

I try to get the value of openMenu from Parent to Child function but the props.value is empty in Child function and I don´t understand why.

function Child({ routes }, props) {

  return (

    <div>{props.value}</div>        /*This is empty*/
  )
}
function Parent() {
  const [isOpen, setOpen] = useState({
    isOpen: false
  });

  const handleClick = e => {
    e.preventDefault();
    setOpen(isOpen => !isOpen);

    if(isOpen === true) {
      const openMenu = 'open';
      return <Child value={openMenu}/>;      
    } 
    else {
      const openMenu = 'close';
      return <Child value={openMenu} />     
    }      

  };
}

I want to get the value of openMenu , either open or close, to the Child component.

Props is the first argument in a function component .

function Child(props) {
  return (   
    <div>{props.value}</div>    
  )
}

If you are trying destructure routes from props you can use the rest pattern ( ... ) to get all other props.

function Child({ routes, ...props }) {
  return (   
    <div>{props.value}</div>    
  )
}

maybe you should have some insight with sending props and destructuring them,

// suppose props = { val1, val2, val3 }

const Parent = (props) => <Child {...props} />

// in such case you can destructure the values in the paranthesis itself,

const child = ({ val1, val2, val3 }) => {
 <div>
  <div>{val1 && val1}</div>
  <div>{val2 && val2}</div>
  <div>{val3 && val3}</div>
 <div>
}


// which is same as,

const child = (props) => {
 const { val1, val2, val3 } = props
 //rest of the code..
}

also you can send multiple props as,

class Parent extends Component {
 // ..
function1 = () => {..}

function2 = () => {..}

 render () {

 //suppose this.props = { match, dispatch, list, ..}
 const value1 = ..
 const value2 = ..

  return <Child {...{ function1, function2, value1, value2}} {...this.props} />
}

and desctructure them in child as,

const Child = ({
 function1,
 function2,
 value1,
 value2,
 match,
 dispatch,
 list,
 }) => {
  return (
   <div> .. </div>
}

now you can see how handy it is, and you won't stumble again.. Note: .. (double dots are fill in the blanks, you know)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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