我正在尝试使用以下样式自定义 TouchableOpacity
<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 文件中自定义此 View 并重用它。无论我想在何处使用它,只需实现 onPress
和 Text
。我怎样才能做到这一点?
最佳答案
这是我创建的其中一个按钮的 fragment 。 textStyle 和 buttonStyle 都在这个组件中被排除在外,但是如果你希望它们是可变的,你可以通过 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,
}
然后 从 '../somepath/Button.js; 导入 { Button };
它将成为可用的自定义 JSX 元素。
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: {
...
}
}
关于android - 如何自定义TouchableOpacity并在各个组件中复用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43678025/