2017-10-18 73 views
2

我已經在我的反應,和/蓋茨比文件下列操作之一:作出反應 - 在點擊更改CSS屬性(箭頭功能)

import React from "react" 

const click =() => { 
    console.log("J"); 
} 

const NavButton =() => 
    <button className="navbar-toggler navbar-toggler-right" style={{backgroundColor: 'blue', position: "absolute", margin: "30px"}}type="button" data-toggle="collapse" data-target="#collapsingNavbar" onClick={click}> 
    <div id="nav-icon1"> 
     <span></span> 
     <span></span> 
     <span></span> 
    </div> 
    </button> 

const Dropdown =() => 
<div style={{visibility: "hidden", backgroundColor: "blue", position: "absolute", height: "100%", width: "100%"}}> 
</div> 

export default (props) => 
    <div className="left col-xs-12 col-md-6"> 
    <Dropdown /> 
    <NavButton /> 
    {props.children} 
    </div> 

現在我想火click()每當有人按下NavButton,然後我想讓Dropdown可見。我將如何做到這一點?現在我有硬編碼Dropdownstyle={{visibility: "hidden", ...

我也想知道我是否正確地做了這件事,如果有人可以告訴我那會很棒!

回答

3

您的控件類需要有狀態:它需要維護布爾狀態,以確定下拉列表是打開還是關閉。當渲染下拉菜單時,如果布爾值已打開,那麼您將顯示下拉菜單,否則您不會。

這是你的代碼重寫來做到這一點。請注意,子組件將道具作爲參數。這是父母與他們溝通的方式。其中一些道具是回調,這是孩子與父母溝通的方式。

import React from "react" 

const NavButton = ({onClick}) => 
    <button className="navbar-toggler navbar-toggler-right" style={{backgroundColor: 'blue', position: "absolute", margin: "30px"}}type="button" data-toggle="collapse" data-target="#collapsingNavbar" onClick={onClick}> 
    <div id="nav-icon1"> 
     <span></span> 
     <span></span> 
     <span></span> 
    </div> 
    </button> 

const Dropdown = ({show}) => 
<div style={{visibility: show ? "visible" : "hidden", backgroundColor: "blue", position: "absolute", height: "100%", width: "100%"}}> 
</div> 

export default class Parent extends React.Component { 
    state = { 
    dropdownVisible: false, 
    }; 

    // toggles the dropdown each time it is called 
    toggleDropdown =() => this.setState(state => ({ 
    dropdownVisible: !state.dropdownVisible, 
    })); 

    render() { 
    return (
     <div className="left col-xs-12 col-md-6"> 
     <Dropdown show={this.state.dropdownVisible} /> 
     <NavButton onClick={this.toggleDropdown} /> 
     {this.props.children} 
     </div> 
    ); 
    } 
} 
+0

完美,謝謝! –