简体   繁体   中英

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.

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

Any ideas if this is possible?

You don't use props in Section component { 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:

<MyComponent props={42}/>

Also, take note that props isn't a reserved keyword or something:

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

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