React Native:子视图未通过状态更改重新加载

时间:2020-07-12 21:56:43

标签: react-native react-hooks use-state

React Native 0.62.2应用程序中的一个组件Itie具有一个子视图组件ButtonInHead。当状态ButtonInHead变为post时,true返回一个启用的保存按钮。这是代码:

import { Button, Left, Right, Body, Icon, Label, Item, Input, Text, Card, CardItem, Header, Container, Content, Form } from 'native-base';


const Itie = () => {  //<<<===component Itie
    const [post, setPost] = useState(false);  //<<<==state post is false initially

    const ButtonInHeader = ({enabled}) => {  //<<<==sub view component 
        if (enabled) {
            return (<Button hasText onPress={clickSave}>
                        <Text>Save</Text>
                    </Button>)
        } else {
            return (<Button hasText disabled >
                        <Text>Save</Text>
                    </Button>)
        };
    };    

    const clickSave = async () => {
          Alert.alert("Save clicked");
    };
    
    return (
        <SafeAreaView> 
            <ScrollView>
                <Container>
                    <Header transparent>
                        <Right>
                            <ButtonInHeader enable={post} /> //<<<==when state post becomes true. button shall be enabled
                        </Right>
                    </Header>
                    <Content>
                        <Form>
                        ......
                        </Form>
                    </Content>
                </Container>
            </ScrollView>
        </SafeAreaView>
    
    );
};

问题是post变成true之后,未重新加载子视图组件ButtonInHead(在android模拟器上)并且按钮保持禁用状态。由于状态post被传递到ButtonInHead中,并且我的理解是,只要post发生变化,ButtonInHead就应该重新加载。显然,这还不是全部。如何在ButtonInHead更改时强制重新加载post

1 个答案:

答案 0 :(得分:0)

通过执行以下操作将状态post引入ButtonInHead中来解决问题:

return (<Button hasText onPress={clickSave} disabled={!post}>
                        <Text>Save</Text>
                    </Button>)

实际上,ButtonInHead不再需要,可以替换为:

<Button hasText onPress={clickSave} disabled={!post}>
                            <Text>Save</Text>
                        </Button>