gpt4 book ai didi

javascript - 如何在 React Native 子组件发生变化时重新渲染父组件?

转载 作者:行者123 更新时间:2023-11-29 15:25:23 26 4
gpt4 key购买 nike

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

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

最佳答案

尝试:

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

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

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

关于javascript - 如何在 React Native 子组件发生变化时重新渲染父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39803041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com