简体   繁体   English

React - 将道具传递给孩子

[英]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.当它是带孩子的 function 时,我不确定如何通过道具。

You need to remove "this" and add the "Enabled" to the function's parameter section.您需要删除“this”并将“Enabled”添加到函数的参数部分。 The reason behind it is you're not using a class-based component.其背后的原因是您没有使用基于类的组件。 There is no need to use "this" in this case.在这种情况下不需要使用“this”。 You have already declared "children" and "onConfirm" in the same way.您已经以相同的方式声明了“children”和“onConfirm”。

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通过像这样定义你的App组件

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

You are Destructuring the argument which will by passed to your Component as usual this argument is named as props .您正在解构将像往常一样传递给您的Component的参数,该参数被命名为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.通过这样做,您将不再访问名为propsproperty ,而只能访问您对在本例中为 props 进行解构的属性所获取的属性。

And on another hand, as you are defining you component as Functional component You don't access properties with the this keyword.另一方面,当您将组件定义为Functional component时,您不能使用this关键字访问属性。

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因此,如果您想访问Enable属性,您必须通过将其添加到您从 arguments props 获得的属性列表中获取 if

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

Or by passing avoiding completly destructation and have access to props instead like this或者通过避免完全破坏并像这样访问props

const App = (props) => ...

By using props you'll have to prefix every properties passed to your Component with props to get access to it.通过使用 props,您必须在传递给Component的每个属性前面加上props才能访问它。 like this像这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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