[英]How do you remove a class from elements inside a component in React.JS when clicking outside given component?
我試圖模擬一種類似於在打開模式彈出窗口時單擊覆蓋的行為。 在 sidenav 組件外部單擊時,我想關閉當前處於flyout
模式的所有元素。
我有一個多層嵌套導航菜單,它存儲在它自己的組件Sidebar
中。 我有以下代碼來處理Sidebar
組件外部發生的clicks
:
class Sidebar extends React.Component {
...
handleClick = (e) => {
if (this.node.contains(e.target)) {
return;
}
console.log('outside');
};
componentDidMount() {
window.addEventListener('mousedown', this.handleClick, false);
}
componentWillUnmount() {
window.removeEventListener('mousedown', this.handleClick, false);
}
render() {
return (
<div
ref={node => this.node = node}
className="sidebar"
data-color={this.props.bgColor}
data-active-color={this.props.activeColor}
>
{renderSideBar()}
</div>
);
}
...
}
這部分工作正常 - 但是當單擊父菜單選項時顯示彈出菜單時,我希望它關閉當前打開的任何彈出菜單。
-|
|
- Menu Item 1
|
|-option 1 (currently open)
|-option 2
- Menu Item 2
|
|-option 1 (closed)
|-option 2 (closed, clicked to expand - this is when it should close [Menu Item 1/Option 1]
在映射包含菜單結構的數據 object 時,使用<li>
標記生成菜單項。
有沒有辦法基本上 select 所有已注冊的具有'collapse' / aria-expanded="true" 的 class 的對象並將其刪除? 類似於jQuery
將 select dom 元素和操作它們的方式。
我知道這不是 React 工作的前提,它只是我想要模仿的行為的一個例子。
據我了解,您想從另一個組件修改 DOM 子樹。 為了實現您的目標,您可以使用ref
。
當您想直接訪問HtmlElement API時,使用ref
很有幫助 - 在我的示例中,我使用animate()
。 請閱讀文檔,因為它描述了更多ref
用例。
下面是當用戶點擊<Content />
時動畫<Sidebar/>
收縮的簡單示例。
const { useRef } = React; function Main() { const sidebar = useRef(null); const handleClick = () => { sidebar.current.hide(); }; return ( <div className="main"> <Sidebar ref={sidebar} /> <Content onClick={handleClick} /> </div> ); } class Sidebar extends React.Component { constructor(props) { super(props); this.state = { visible: true }; this.show = this.show.bind(this); this.sidebar = React.createRef(null); } show() { if (.this.state.visible) { this.sidebar.current:animate( { flex, [1, 2]: "background-color", ["teal", "red"] }; 300 ). this:setState({ visible; true }). } } hide() { if (this.state.visible) { this.sidebar.current:animate( { flex, [2, 1]: "background-color", ["red", "teal"] }; 300 ). this:setState({ visible; false }). } } render() { return ( <div ref={this.sidebar} className={this.state?visible: "sidebar--visible". "sidebar"} onClick={this;show} > Sidebar </div> ); } } function Content({ onClick }) { return ( <div className="content" onClick={onClick}> Content </div> ). } ReactDOM,render(<Main />. document;getElementById("root"));
.main { display: flex; height: 100vh; }.sidebar { flex: 1; background-color: teal; }.sidebar--visible { flex: 2; background-color: red; }.content { flex: 7; background-color: beige; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.