React Native 0.62.2应用程序中的一个组件
Itie
有一个子视图组件ButtonInHead
。当状态post
变为true
时,ButtonInHead
返回启用的保存按钮。这是代码:
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
。显然,这并不是全部。如何在post
发生变化时强制重新加载ButtonInHead
?
通过执行以下操作将状态post
引入ButtonInHead
解决的问题:
return (<Button hasText onPress={clickSave} disabled={!post}>
<Text>Save</Text>
</Button>)
实际上,ButtonInHead
已不再需要,可以替换为:
<Button hasText onPress={clickSave} disabled={!post}>
<Text>Save</Text>
</Button>