简体   繁体   中英

React - Pass props to children

I am trying to do a conditional statement. However, I am having difficulty passing through the props

const App = ({children, onConfirm}) => {
{modalActive && renderModal(() => setModalActive(false), () => { onConfirmAbort(); setModalActive(false); })}

 if (this.props.Enabled("True")) {
    return (
        <h1>hello world </h1>
    );
  }
  return (
    <div>
        {children}
    </div>
  );
};

This will give me the error:

TypeError: Cannot read property 'props' of undefined.  

I am not sure how to pass props through when it is a function with children.

You need to remove "this" and add the "Enabled" to the function's parameter section. The reason behind it is you're not using a class-based component. There is no need to use "this" in this case. You have already declared "children" and "onConfirm" in the same way.

const App = ({children, onConfirm, Enabled}) => {
{modalActive && renderModal(() => setModalActive(false), () => { onConfirmAbort(); setModalActive(false); })}

 if (Enabled("True")) {
    return (
        <h1>hello world </h1>
    );
}
return (
    <div>
        {children}
    </div>
);

};

By defining you App component like this

const App = ({children, onConfirm}) => {
    // ...
}

You are Destructuring the argument which will by passed to your Component as usual this argument is named as props . By doing that you haven't no longer access to the property named props but only to the properties which you took of the property which is destructured in this case props.

And on another hand, as you are defining you component as Functional component You don't access properties with the this keyword.

So if you want to get access to the Enable property you have to get if from props by adding it to the list of properties which you get from arguments props which is been destructured like this

const App = ({children, onConfirm, Enabled}) => ...

Or by passing avoiding completly destructation and have access to props instead like this

const App = (props) => ...

By using props you'll have to prefix every properties passed to your Component with props to get access to it. like this

props.children, props.onConfirm, props.Enabled(...)

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