如何自定义 TouchableOpacity 并在每个组件中重用 [英] How to customize TouchableOpacity and reuse in each component
问题描述
我正在尝试使用以下样式自定义 TouchableOpacity
I am trying to customize TouchableOpacity
with below style
<TouchableOpacity
onPress={() => {
navigate("EnableNotification");
}}
>
<View
style={{
backgroundColor: "#FE434C",
alignItems: "center",
justifyContent: "center",
borderRadius: 10,
width: 240,
marginTop: 30,
height: 40
}}
>
<Text style={{ color: "white" }}>CONTINUE</Text>
</View>
</TouchableOpacity>
我在每个组件中都有这个 TouchableOpacity
.我想要在一个 js 文件中自定义这个视图 &重用这个.无论我想在哪里使用它,只需实现 onPress
和 Text
.我怎样才能做到这一点?
I have this TouchableOpacity
in each component. I want something like customize this view in one js file & reuse this. Wherever I want to use this simply implement onPress
and Text
. How can I achieve this ?
推荐答案
这是我创建的其中一个按钮的片段.textStyle &buttonStyle 都在这个组件中被排除在外,但如果你希望它们是可变的,你可以通过 RoundButton = ({ textStyle, buttonStyle })
Here's a snippet of one of the buttons I have created. The textStyle & buttonStyle are both in this component excluded, but if you wanted them to be variable you would pass it through RoundButton = ({ textStyle, buttonStyle })
const RoundButton = ({ onPress, children }) => {
return (
<TouchableOpacity onPress={onPress} style={buttonStyle}>
<Text style={textStyle}>{children}</Text>
</TouchableOpacity>
);
};
这是一个用例:
<RoundButton onPress={this.onSubmit.bind(this)>Confirm</RoundButton>
所以,你可以去:
const Button = ({ onPress, buttonText }) => {
const { buttonStyle, textStyle } = styles;
return (
<TouchableOpacity onPress={onPress} style={styles.button}>
<Text style={{ color: '#fff' }}>{buttonText}</Text>
</TouchableOpacity>
);
};
const styles = {
backgroundColor: '#FE434C',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 10,
width: 240,
marginTop: 30,
height: 40,
}
then import { Button } from '../somepath/Button.js;
它将是一个可用的自定义 JSX 元素.
Where it will be a useable custom JSX element.
return (
...
<Button onPress={() => navigate('EnableNotification'}>CONTINUE</Button>
...
)
更新传递样式:
const Button = ({ onPress, buttonText, buttonStyle, textStyle }) => {
return (
<TouchableOpacity onPress={onPress} style={buttonStyle}>
<Text style={textStyle}>{buttonText}</Text>
</TouchableOpacity>
);
};
您的用例是:
import { Button } from '../somepath/Button.js';
class MyPage extends Component {
render() {
return (
...
<Button buttonStyle={styles.yourStyle} textStyle={styles.yourStyle2} onPress={() => navigate('EnableNotification')>CONTINUE</Button>
...
)
}
}
const styles = {
yourStyle: {
...
}
yourStyle2: {
...
}
}
这篇关于如何自定义 TouchableOpacity 并在每个组件中重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!