React Native:子视图未随状态更改而重新加载


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>

相关内容

  • 没有找到相关文章

最新更新