需要从另一个组件呈现侧边栏组件onclick()

时间:2019-08-04 16:52:10

标签: reactjs onclick sidebar eventhandler

我是新来的反应者,我有一个侧栏组件,我试图通过单击按钮从另一个组件内部进行渲染,我取得了一些成功,但是,解决方案并不完美,侧栏打开了单击,但只执行一次,刷新页面后便可以再次使用

    //this is sidebar.js  
    class SideBar extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                sidebarOpen: true,
                sidebar: null
            };
            this.onSetSidebarOpen = this.onSetSidebarOpen.bind(this);
        }

        onSetSidebarOpen(open) {
            this.setState({ sidebarOpen: open });
        }

        render() {
            return (
                <Sidebar
                    sidebar={<b>Sidebar content</b>}
                    open={this.state.sidebarOpen}
                    onSetOpen={this.onSetSidebarOpen}
                    styles={{ sidebar: { background: "white" } }}
                >
                </Sidebar>
            );
        }
    }

//这就是我的访问方式

  class EventCard extends React.Component{
       constructor(props) {
       super(props);
       //this.state = { isAboutVisible:null};
    }

    state = {
        isAboutVisible: false,
      }

    render(){
        const {title, type, description, icon } = this.props.event;
        return (
            <div ref={this.eventRef}>
                <span>{title}</span>
                <p>{type}</p>
                <img 
                alt={description}
                src={icon}
                />
                 <button onClick={() => this.setState({isAboutVisible: true})}>More Info</button>
                 { this.state.isAboutVisible ? <SideBar /> : <div></div> }
                <button>Delete</button>           
            </div>
        );
    }
}

export default EventCard;

///单击按钮后出现此错误:

index.js:1375 Warning: Failed prop type: The prop `children` is marked as required in `Sidebar`, but its value is `undefined`.
    in Sidebar (at SideBar.js:19)
    in SideBar (at EventCard.js:21)
    in div (at EventCard.js:13)
    in EventCard (at EventList.js:7)
    in div (at EventList.js:11)
    in EventList (at App.js:19)
    in div (at App.js:17)
    in App (at src/index.js:7)

2 个答案:

答案 0 :(得分:0)

您的代码(如果还不清楚),我想您需要执行以下操作:

onSetSidebarOpen(open) {
        this.setState({ sidebarOpen: !this.state.sidebarOpen });
    }

答案 1 :(得分:0)

根据此docs

您忘记将button添加到Sidebar,需要将{{1}作为button添加到children

Sidebar

Demo