你好,我分裂我的應用程序,並希望從我的<button />
到<menu />
狀態通過我只是試圖做的是切換一個函數與onClick。反應如何將狀態傳遞到另一個組件
所以Button.js文件將有1個按鈕,當點擊將切換狀態爲可見或不可見。菜單組件Menu.js需要了解這些狀態的變化,使他們能夠切換功能,並會顯示菜單
Button組件
import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './NavButton.scss';
@themr('NavButton', localStyles)
export default class NavButton extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false,
};
this.toggleMenu = this.toggleMenu.bind(this);
}
toggleMenu() {
this.setState({
visible: !this.state.visible
})
console.log('toggle');
}
render() {
const {theme } = this.props;
return (
<div className={theme['nav-button']} onClick={this.toggleMenu}>
<span></span>
<span></span>
</div>
);
}
}
菜單
import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './Menu.scss';
import { NavButton } from '../../components';
@themr('Menu', localStyles)
export default class Menu extends React.Component {
render() {
return (
<div className="menu-wrapper">
<CSSTransitionGroup
transitionName="menu"
transitionEnterTimeout={300}
transitionLeaveTimeout={300}>
{this.state.visible &&
<Menus alignment="right">
<MenuItem hash="first-page">First Page</MenuItem>
<MenuItem hash="second-page">Second Page</MenuItem>
<MenuItem hash="third-page">Third Page</MenuItem>
</Menus>}
</CSSTransitionGroup>
</div>
);
}
}
const Menus = ({alignment, children, theme }) => (
<div className="menu">
<div className={alignment}>{children}</div>
</div>
);
您的Menu.js與Button.js相同 – user2340824
按鈕和菜單如何連接在一起?你可以添加你的容器組件嗎? 您可以將狀態保持在容器上的一個位置,通過切換狀態作爲道具菜單。 –
即時通訊導入按鈕組件到我的菜單,並希望改變this.state.visible點擊按鈕,我也更新了我的代碼 – Alex