reactjs React/Redux.从其他组件访问状态

dly7yett  于 2022-11-22  发布在  React
关注(0)|答案(1)|浏览(132)

我尝试从另一个组件访问组件状态,但没有成功。到目前为止,我的代码如下所示:
这两个组件呈现在App.js中,即入口文件。第一个组件是一个移动的导航。这个组件应该是打开/关闭的,这取决于组件2中的状态,组件2是一个切换按钮。有人能帮我吗?
组件1。(在这里,我想访问组件2的“toggled”状态)

import * as style from './MobileNavigation.style'
import React, { Component } from 'react'
import Button from '../../components/Button'

class MobileNavigation extends Component {
render() {
return (
  <style.Background>
    <style.Menu>
      <style.MenuItem>
        <style.RouterLink to="home">home</style.RouterLink>
      </style.MenuItem>
      <style.MenuItem>
        <style.RouterLink to="about">about</style.RouterLink>
      </style.MenuItem>
      <style.MenuItem>
        <style.RouterLink to="contact">contact</style.RouterLink>
      </style.MenuItem>
    </style.Menu>
  </style.Background>
)
  }
}

export default MobileNavigation

第二部分

import React, { Component } from 'react'
import styled from 'styled-components'
import * as style from './Hamburger.style'

interface Props {
  width: string
  height: string
  fill: string
  toggled?: boolean
}

interface State {
  toggled?: boolean
}

const Svg = styled.svg`
  width: ${(props: Props) => props.width};
  height: ${(props: Props) => props.height};
`

class Hamburger extends Component<Props, State> {
  static defaultProps = {
    width: '100%',
    height: '100%',
    fill: '#172b41',
    toggled: true
  }

  constructor(props: any) {
    super(props)
    this.state = {
      toggled: true
    }
  }

  onClick(toggled: boolean) {
    this.setState({
      toggled: !this.state.toggled,
    })
  }

  render() {
    return (
      <style.Wrapper onClick={this.onClick.bind(this, this.props.toggled)}>
    {this.state.toggled ? (
      <div>closed</div>
    ) : (
      <div>open</div>
    )}
  </style.Wrapper>
)
}
}

export default Hamburger
nhaq1z21

nhaq1z211#

# React 方式 :

如果 你 想 自己 做出 React( 不 使用 redux ) 您 需要 在 父 组件 中 创建 shouldToggled 的 状态 和 控制 它 的 函数( App.js ) 的 数据 。然后 你 需要 把 函数 传递 给 你 的 汉堡 包 组件 , 把 状态 传递 给 另 一 个 , 在 你 的 汉堡 包 组件 中 , 你 需要 用 函数 来 改变 你 的 App.js 组件 的 状态 , 这样 你 的父 状态 将 被 更新 , 并 将 导致 重新 渲染 。 这 被 称为 提升 状态 技术 , 你 可以 在 React 文档 中 看到 它 以 获得 更 多 信息 。

# 还原 方式 :

redux 的 方式 有点 复杂 , 你 有 两 种 选择 , 一 种 是 基于 组件 的 父/子 关系 的 复杂 性 , 另 一 种 是 你 的 子 有 多 深( 在 您 的 情况 下 , 这 只是 一 个 层次 的 深度 ) , 与 react 方式 相同 , 您 需要 在 * * redux store * * 上 有 一 个 状态 来 控制 组件 的 切换 状态 , 并且 还 需要 有 一 个 操作 创建 器 ,为了 触发 状态 的 改变 , 在 你 的 汉堡 包 组件 中 , 你 需要 调用 action creator 来 发送 action 到 reducer , 以便 改变 存储 , 一旦 存储 以 不可 变 的 方式 改变 , 整个 redux 存储 将 被 更新 并 立即 提供 给 你 的 整个 应用 程序 , 最 后 将 导致 你 的 组件 的 重新 呈现 。

# 终于 :

确保 只 在 复杂 情况 下 使用 redux 方法 , 你 会 发现 它 在 那些 情况 下 很 有用 , 而 不是 在 像 你 现在 的 问题 这样 的 简单 情况 下 。 我 对 你 的 建议 是 :坚持 使用 react 提升 状态 技术 来 解决 你 当前 的 问题 , b/c 它 在 你 的 情况 下 需要 少 得 多 的 锅炉 板 代码 。

相关问题