【问题标题】:How to re-render parent component on change on sub component in react native?如何在反应原生的子组件上重新渲染父组件?
【发布时间】:2017-02-09 17:05:17
【问题描述】:

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

在下面的示例中,来自第二个组件的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>
    );
  }
}

【问题讨论】:

    标签: javascript react-native components render


    【解决方案1】:

    试试:

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

    或者如果你使用的是 ES5:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      • 2019-06-01
      • 2018-09-19
      • 2021-01-24
      • 2020-02-13
      • 2018-08-12
      • 1970-01-01
      相关资源
      最近更新 更多