如何在native native中更改子组件上的父组件?

时间:2016-10-01 04:30:04

标签: javascript react-native components render

我有一个渲染另一个组件的组件。当我对子组件进行更改时,我希望重新渲染主要组件。

在第二个组件中的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 个答案:

答案 0 :(得分:1)

尝试:

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

或者如果您使用的是ES5:

_onSubmit(data) {
  this.setState({ data: data }, function () {
    this.forceUpdate();
  }.bind(this));
}