我使用setState
是为了在React Native中按下按钮时动态更新图像的来源。但是,我还使用TypeWriter库,该库使用特殊的“打字机”动画效果来键入文本。
当调用我的setState更改元素并重新呈现页面时,TypeWriter再次键入文本。我不要这个有没有一种方法可以排除我的TypeWriter文本而无法重新渲染?
代码段:
export const AccountScreen = ({ navigation }) => {
this.state = {
img1Src: require('../assets/img/token.png')
}
const [state, setState] = useState(this.state);
changeImgSrc = () =>{
setState({
img1Src: require('../assets/img/X2.png')
})
}
return (
<TypeWriter> //I don't want this to re-render on setState
<Text>My Account</Text>
</TypeWriter>
<Animatable.Image source={state.img1Src}/>
<Button onPress={this.changeImgSrc}>
Click me!
</Button>
etc...//
答案 0 :(得分:1)
export const NewComponent = ({ navigation }) => {
const [state, setState] = useState({
img1Src: require('../assets/img/token.png')
});
changeImgSrc = () =>{
setState({
img1Src: require('../assets/img/X2.png')
})
}
return (
<Animatable.Image source={state.img1Src}/>
<Button onPress={this.changeImgSrc}>
Click me!
</Button>
etc...//
您可以使一个新组件称为NewComponent。然后,
export const AccountScreen = ({ navigation }) => {
return (
<TypeWriter> //I don't want this to re-render on setState
<Text>My Account</Text>
</TypeWriter>
<NewComponent />
etc...//
此外,您不能在功能组件中使用它。另外,如果要在功能组件中调用函数,则必须将其与useCallback一起使用。