简体   繁体   English

在子组件道具上使用父道具

[英]Use parent prop on child component prop

I have this code :我有这个代码:

import React from "react"
import sectionStyles from "./section.module.css"
import Title from "../title/title"

export default ({ children }) => (
  <div className={sectionStyles.container}>
    <Title titleText={props.sectionText}></Title>
    {children}
  </div>
)

So in the page I can do :所以在页面中我可以这样做:

<Section sectionText="Skills"></Section>;

The sectionText="Skills" will go pass down to the title component prop and render the text from the parent prop. sectionText="Skills"将向下传递到标题组件道具并渲染来自父道具的文本。

I want to be able to use title as a standalone component and inside section parent component.我希望能够将标题用作独立组件和内部部分父组件。

I am getting :我正进入(状态 :

error 'props' is not defined no-undef错误 'props' 未定义 no-undef

Any ideas if this is possible?如果可能的话,有什么想法吗?

You don't use props in Section component { children, ...props } :您不在Section组件{ children, ...props }使用道具:

import React from "react";
import sectionStyles from "./section.module.css";
import Title from "../title/title";

// I think its the best approach,
// destruct the necessary props and style with the rest.
// now you can style title from its parent
export default ({ children, sectionText, ...props }) => (
  <div className={sectionStyles.container}>
    <Title {...props} titleText={sectionText}></Title>
    {children}
  </div>
)

// When there are too many props used inside the component
export default props => {
  const { children, sectionText, ..., ... ,... } = props;
  return (
    <div className={sectionStyles.container}>
      <Title titleText={sectionText}></Title>
      {children}
    </div>
  );
};

// Tomato tomato
export default ({ children, ...props }) => (
  <div className={sectionStyles.container}>
    <Title titleText={props.sectionText}></Title>
    {children}
  </div>
);

export default ({ children, sectionText }) => (
  <div className={sectionStyles.container}>
    <Title titleText={sectionText}></Title>
    {children}
  </div>
)

export default props => (
  <div className={sectionStyles.container}>
    <Title titleText={props.sectionText}></Title>
    {props.children}
  </div>
);

In case you don't destruct props:如果您不破坏道具:

export default ({ children, props }) => (...);

The ReactElement will consider props as a property: ReactElement会将props视为一个属性:

<MyComponent props={42}/>

Also, take note that props isn't a reserved keyword or something:另外,请注意props不是保留关键字或其他东西:

export default ({ children, ...rest }) => (
  <div className={sectionStyles.container}>
    <Title titleText={rest.sectionText}></Title>
    {children}
  </div>
)

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

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