![](/img/trans.png)
[英]How can I add styling to an event listener in an class component in React?
[英]How can I add my own event listener to my custom React Native component?
所以我使用 React Native+Expo 並且我制作了一個自定義組件,它是一個步進器。 看起來像這樣:
這是它的代碼:
import React, { useState } from 'react';
import { View, Text,StyleSheet, TouchableOpacity } from 'react-native';
const Stepper = (props) => {
let counter = 0;
const increment = () => {
counter += 1
}
const decrement = () => {
counter -= 1
}
return (
<View style={{ ...styles.stepperStyle, ...props.containerStyle }}>
<TouchableOpacity style={{
backgroundColor: props.leftColor,
flex: 1,
alignItems: 'center',
justifyContent: 'center',
borderTopLeftRadius: props.radius,
borderBottomLeftRadius: props.radius
}}>
<Text adjustsFontSizeToFit={true} style={{ fontSize: 40 }}>-</Text>
</TouchableOpacity>
<View style={{
borderLeftWidth: 1,
borderRightWidth: 1,
alignItems: 'center',
justifyContent: 'center',
flex: 1
}}>
<Text style={props.labelStyle}>{props.initialValue} {props.label}</Text>
</View>
<TouchableOpacity style={{
backgroundColor: props.rightColor,
flex: 1,
alignItems: 'center',
justifyContent: 'center',
borderTopRightRadius: props.radius,
borderBottomRightRadius: props.radius
}}>
<Text adjustsFontSizeToFit={true}
style={{ fontSize: 40 }}>+</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
stepperStyle: {
backgroundColor: 'transparent',
flexDirection: 'row',
borderRadius: 100,
borderWidth: 1,
width: '100%',
height: 42
}
});
export default Stepper
我想要做的是制作某種事件偵聽器或函數,可以在計數器值發生變化時返回它。
所以從外面看,我希望它看起來像這樣:
<Stepper
onValueChange={count => setSets(count)}
/>
我剛開始做這樣的事情。 我需要使用 useEffect 鈎子嗎? 獲取當前計數器值的最佳方法是什么? 任何幫助,將不勝感激!
由於看起來您希望組件內部的值與組件外部的有狀態sets
值相匹配,因此處理此問題的最合理方法是將sets
和setSets
作為 props 向下傳遞,並通過increment
和decrement
使用和調用它們.
<Stepper
{...{ sets, setSets }}
/>
const Stepper = ({ sets, setSets }) => {
const increment = () => setSets(sets + 1);
const decrement = () => setSets(sets - 1);
// other code that references increment and decrement and sets
如果外部狀態名稱可以更改,請使用
<Stepper
counter={sets} setCounter={setSets}
/>
const Stepper = ({ counter, setCounter }) => {
const increment = () => setCounter(counter + 1);
const decrement = () => setCounter(counter - 1);
// other code that references increment and decrement and counter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.