2016-10-01 95 views
1

我有一個呈現另一個組件的組件。當我對子組件進行更改時,我希望主要組件重新呈現。如何在原生反應的子組件上重新生成父組件?

在下面onSubmit從第二部件的例子中,觸發_onSubmit的主要成分,但setState不重新呈現視圖

想法?

class MainLayout extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     data: 'no', 
    }; 

    this._onSubmit = this._onSubmit.bind(this); 
    } 

    // this get's triggered by _checkSubmitReady() on the second component 
    _onSubmit(data) { 
    // this state get's set, but this component is not re-rendered 
    // i assume render() should be called here 
    this.setState({data: data}); 
    } 

    render() { 
    return (
     <View><SecondLayout onSubmit={this._onSubmit}/>{this.state.data}</View> 
    ); 
    } 
} 


class SecondLayout extends Component { 
    constructor(props) { 
    super(props); 

    this._checkSubmit = this._checkSubmit.bind(this); 
    } 

    _checkSubmit() { 
    this.props.onSubmit('yes'); 
    } 

    // sub component is mounted, call onSubmit() on parent component 
    componentDidMount() { 
    this._checkSubmit(); 
    } 

    render() { 
    return (
     <View><Text>Nothing here</Text></View> 
    ); 
    } 
} 

回答

1

嘗試:

_onSubmit(data) { 
    this.setState({ data: data },() => { 
    this.forceUpdate(); 
    }); 
} 

或者,如果您使用的是ES5:

_onSubmit(data) { 
    this.setState({ data: data }, function() { 
    this.forceUpdate(); 
    }.bind(this)); 
} 
相關問題