2016-12-26 26 views
0

我試圖改變一個子組件中的狀態,每次我調用它的父組件中的一個函數。我會如何去做這件事?例如,如何通過在其父級調用函數來更改子組件中的狀態?

class ParentComponent extends Component { 
function onClick(){ 
    // some function here to change child components state 
} 
render(){ 
    return (
     <div> 
     <ChildComponent /> 
     <button onClick={this.onClick.bind(this)}> 
     </div> 
     ) 
    } 

class ChildComponent extends Component { 
constructor(props){ 
    super(props) 
    this.state = { 
    MyState: 1 
    } 
} 
render(){ 
    return(
    <div> 
     {this.state.MyState} 
    </div> 
) 
} 
} 

回答

1

根據我的理解,你正在努力實現這一點:

class ParentComponent extends Component { 
constructor(props){ 
    super(props) 
    this.state = { 
    MyState: 1 
    } 
} 

function onClick(){ 
    this.setState({MyState:this.state.MyState + 1}) 
} 
render(){ 
    return (
     <div> 
     <ChildComponent sendToChild={this.state.MyState}/> 
     <button onClick={this.onClick.bind(this)}> 
     </div> 
     ) 
    } 

class ChildComponent extends Component { 

render(){ 
    return(
    <div> 
     {this.props.MyState} 
    </div> 
) 
} 
} 
0

呼叫的setState在onClick處理程序 - 這將導致在爲父級一個重新呈現以及任何子組件(除非組件在shouldComponentUpdate返回假,但是你沒有這個功能實現) 。但是,即使當前由於沒有道具而重新渲染,您的孩子組件也不會在視覺上發生變化。

不知道你想要什麼,實現準確的,但如果你的狀態MyState從ChildComponent移動到爲父級,並通過MyState爲道具,以ChildComponent,並在onClick處理程序調用setState並增加MyState然後ChildComponent視覺上會更新。

0

將您的onClick處理程序放入子組件中,lift the state up或通過onClick通過道具。

你想完成什麼?

+0

的問題是,我想執行'onClick'處理父組件內,因此把的onClick處理程序在我的孩子組件不會是理想的。通過道具傳遞'onClick'不會很理想,因爲我試圖讓這個函數改變子組件的狀態,而不是父母。 –

相關問題