简体   繁体   English

在React中管理嵌套组件中的状态

[英]Managing states in nested components in react

I have the following structure, where in my headButtons component I am trying to receive a prop to change a state in my ProfileDetail 我具有以下结构,在我的headButtons组件中,我试图接收支持更改ProfileDetail状态的道具。

  • TitleContainer TitleContainer

    • headButtons.js headButtons.js
    • TitleContainer.js TitleContainer.js
  • Profile Detail 个人资料详细信息

    • ProfileDetail.js ProfileDetail.js

HeadButtons.js HeadButtons.js

const HeadButtons = ({ action }) => {
  return (
    <Buttons>
      <li>
        <Link to="#">Export</Link>
      </li>
      <li className="active">
        <Link to="#" onClick={action}>Add</Link>
      </li>
    </Buttons>
  )}

and I am importing this component inside my TitleContainer 我将这个组件导入TitleContainer

import HeadButtons from './HeadButtons'
const TitleContainer = ({ title }) => {
  return (
    <Container>
      <PageTitle>
        { title }
      </PageTitle>
      <HeadButtons />
     </Container>
  )
}

and in my UserProfileDetail Im importing both components. 并在我的UserProfileDetail Im中导入这两个组件。

export class UserProfileDetail extends Component {

state = {
  ShowModal: false
}

openModal = () => {
  this.setState({
    ShowModal: !ShowModal
  })
}


<TitleContainer title={ userName } action={this.openModal} />

What I am not understanding is why my component TitleContainer cant execute the openModal to change the state of ShowModal . 我不明白的是为什么我的组件TitleContainer无法执行openModal来更改ShowModal的状态。

Any directions ? 有方向吗?

While rendering HeadButton component in TitleContainer , you aren't passing down the action as prop to it. 虽然渲染HeadButton在组件TitleContainer ,你是不是传承的行动道具吧。

import HeadButtons from './HeadButtons'
const TitleContainer = ({ title, action }) => {
  return (
    <Container>
      <PageTitle>
        { title }
      </PageTitle>
      <HeadButtons action={action}/>
     </Container>
  )
}

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

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