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

时间:2019-08-09 13:44:22

标签: javascript reactjs

我有以下代码:

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

所以在页面上我可以做:

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

sectionText="Skills"将向下传递到标题组件prop,并渲染来自父prop的文本。

我希望能够将title用作独立组件并在节的父组件内部使用。

我得到了:

  

错误'props'未定义为un-undef

有什么可能的想法吗?

1 个答案:

答案 0 :(得分:1)

您没有在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>
);

如果您不破坏道具:

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

ReactElement会将props视为属性:

<MyComponent props={42}/>

另外,请注意,props不是保留关键字或其他内容:

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