反应-将道具传递给孩子

时间:2020-07-13 10:51:24

标签: javascript reactjs

我正在尝试执行条件语句。但是,我在穿过道具时遇到困难

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>
  );
};

这会给我错误:

TypeError: Cannot read property 'props' of undefined.  

当带有孩子的功能时,我不确定如何传递道具。

2 个答案:

答案 0 :(得分:1)

您需要删除“ this”并将“ Enabled”添加到函数的参数部分。其背后的原因是您没有使用基于类的组件。在这种情况下,无需使用“ this”。您已经以相同的方式声明了“儿童”和“ 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>
);

};

答案 1 :(得分:1)

通过这样定义您的App组件

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

您正在解构参数,该参数将照常传递给您的Component,该参数命名为props。这样一来,您将无法再访问名为property的{​​{1}},而只能访问您所获取的属性(在本例中为props)。

另一方面,在将组件定义为props时,您不会使用Functional component关键字访问属性。

因此,如果您想访问this属性,则必须从props获取属性,方法是将其添加到从参数props中获得的属性列表中,该属性已像这样被结构化

Enable

或者通过避免完全破坏而通过访问const App = ({children, onConfirm, Enabled}) => ... 代替

props

通过使用道具,您必须在传递给const App = (props) => ... 的每个属性前面加上Component才能访问它。像这样

props