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