在React Native中使用状态和道具

问题描述 投票:-2回答:2

我可以在App.js中使用子组件状态吗?我的意思是,在一个子组件中我有一个变量,例如i = 5,我想在App.js中使用它。在App.js中,this.state.i显示0。

react-native
2个回答
0
投票

这是一个非常基本的反应模式,所以也许只需阅读官方文档或者做一些反应入门教程。

但是为了帮助你解决这个问题,你需要向你的孩子传递一个函数来设置<App/>中的状态

所以像这样:

应用程序:


    this.state { i : 0 }

    updateState() {
        this.setState(i: i + 1); // or whatever
    }

    render() {
        return (
            <>
                 <Child updateState={this.updateState} />
            </>
    ....

儿童:

<div onClick={props.updateState}>Click me</div>

0
投票

在app.js上这样做;

constructor(props) {
this.updateI=this.updateI.bind(this)
    super(props)
    this.state = {
       i:0
    }
}

        updateI(i){
         this.setState({i})
    }

    render() {
            return (
                <View >
                        <Child updateI={this.updateI}/>
                </View>
            )
        }

对你的孩子这样做:

this.props.updateI(5);
© www.soinside.com 2019 - 2024. All rights reserved.