2017-04-22 78 views
1

我在React JS中有一個簡單的問題。我有兩個不同的點擊事件,它們切換組件的狀態。第一個完美的工作,但我不能得到第二個事件重置組件回到其原始狀態。這是我的問題的簡化版本,所以只知道我不能將點擊功能移動到Child組件中。在React中重置組件的狀態

class Parent extends Component{ 
    constructor(){ 
    this.state = { 
     open: false 
    } 
    this.handleOpen = this.handleOpen.bind(this) 
    this.handleClose = this.handleClose.bind(this) 
    } 
    handleOpen(){ 
    this.setState({open: true}) 
    } 
    handleClose(){ 
    this.setState({open: false}) 
    } 
    render(){ 
    return(
    <div> 
     <Child onOpen={this.handleOpen} onClose={this.handleClose} /> 
     <Child onOpen={this.handleOpen} onClose={this.handleClose} /> 
     <Child onOpen={this.handleOpen} onClose={this.handleClose} /> 
     <Child onOpen={this.handleOpen} onClose={this.handleClose} /> 
    </div> 
    ) 
    } 
} 

就像我說的,handleOpen功能切換狀態,但handleClose不切換回來。我可以獲得一個控制檯日誌以顯示handleClose函數,所以我知道它不必關心它是如何連接到子組件的。我錯過了關於如何在已經切換之後重置狀態值的情況。感謝您的幫助!

+0

你需要用你的孩子在一個''

+1

你實際上調用'render'的功能。當然你的意思是傳遞函數參考'onOpen = {this.handleOpen}'< - 沒有圓括號 – azium

+0

對不起,這些都是錯別字。它們已被修復,但問題仍然存在。有任何想法嗎? –

回答

0

這是您如何做到這一點!

class Child extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    this.handleClick = this.handleClick.bind(this); 
 
    } 
 
    
 
    handleClick() { 
 
     console.log(this.props.isOpen); 
 
     if (this.props.isOpen) { 
 
     this.props.onClose(); 
 
     } else { 
 
     this.props.onOpen(); 
 
     } 
 
    } 
 

 
    render() { 
 
     return <button onClick={this.handleClick}>Click ME</button>; 
 
    } 
 
} 
 

 
class Parent extends React.Component{ 
 
    constructor(props){ 
 
    super(props); 
 
    this.state = { 
 
     open: false 
 
    } 
 
    this.handleOpen = this.handleOpen.bind(this) 
 
    this.handleClose = this.handleClose.bind(this) 
 
    } 
 
    handleOpen(){ 
 
    this.setState({open: true}) 
 
    } 
 
    handleClose(){ 
 
    this.setState({open: false}) 
 
    } 
 
    render(){ 
 
    return(
 
    <div> 
 
     <p>{this.state.open.toString()}</p> 
 
     <Child onOpen={this.handleOpen} onClose={this.handleClose} isOpen={this.state.open} /> 
 
     <Child onOpen={this.handleOpen} onClose={this.handleClose} isOpen={this.state.open} /> 
 
     <Child onOpen={this.handleOpen} onClose={this.handleClose} isOpen={this.state.open} /> 
 
     <Child onOpen={this.handleOpen} onClose={this.handleClose} isOpen={this.state.open} /> 
 
    </div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <Parent/>, 
 
    document.getElementById('container') 
 
);