简体   繁体   中英

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

  • TitleContainer

    • headButtons.js
    • TitleContainer.js
  • Profile Detail

    • ProfileDetail.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

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

and in my UserProfileDetail Im importing both components.

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 .

Any directions ?

While rendering HeadButton component in TitleContainer , you aren't passing down the action as prop to it.

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

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