在功能组件中如何完成同样的事情?
How same thing can be done in functional component?
我在基于 class 的组件中获取输出,但我想知道如何在功能组件中完成同样的事情
class Apps extends React.Component {
handleViewRef = ref => this.view = ref;
bounce = () => this.view.bounce(800)
render() {
return (
<View style={{margin:60}}>
<TouchableWithoutFeedback onPress={this.bounce}>
<Animatable.View ref={this.handleViewRef}>
<Text>Bounce me!</Text>
</Animatable.View>
</TouchableWithoutFeedback>
</View>
);
}
}
您需要使用钩子来实现:
const App = ()=>{
const const viewRef = useRef(null);
const bounce = useCallback(() => {
if (viewRef.current) {
viewRef.current.bounce(800)
}, [viewRef]
);
return (
<View style={styles.container}>
<TouchableWithoutFeedback onPress={bounce} style={styles.container}>
<Button ref={viewRef} rounded warning>
<Text>Warning</Text>
</Button>
</TouchableWithoutFeedback>
<Apps/>
</View>
);
}
useCallback
并非绝对必要,但会阻止在每次渲染时重新创建 bounce
回调。参见 https://reactjs.org/docs/hooks-reference.html#useref and https://reactjs.org/docs/hooks-reference.html#usecallback
我在基于 class 的组件中获取输出,但我想知道如何在功能组件中完成同样的事情
class Apps extends React.Component {
handleViewRef = ref => this.view = ref;
bounce = () => this.view.bounce(800)
render() {
return (
<View style={{margin:60}}>
<TouchableWithoutFeedback onPress={this.bounce}>
<Animatable.View ref={this.handleViewRef}>
<Text>Bounce me!</Text>
</Animatable.View>
</TouchableWithoutFeedback>
</View>
);
}
}
您需要使用钩子来实现:
const App = ()=>{
const const viewRef = useRef(null);
const bounce = useCallback(() => {
if (viewRef.current) {
viewRef.current.bounce(800)
}, [viewRef]
);
return (
<View style={styles.container}>
<TouchableWithoutFeedback onPress={bounce} style={styles.container}>
<Button ref={viewRef} rounded warning>
<Text>Warning</Text>
</Button>
</TouchableWithoutFeedback>
<Apps/>
</View>
);
}
useCallback
并非绝对必要,但会阻止在每次渲染时重新创建 bounce
回调。参见 https://reactjs.org/docs/hooks-reference.html#useref and https://reactjs.org/docs/hooks-reference.html#usecallback