gpt4 book ai didi

android - React Native 中的平台特定组件

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:29 24 4
gpt4 key购买 nike

我很确定这很简单,但我不太明白如何将它们组合在一起。目前我的应用程序在 iOS 中完美运行,但我使用了一些与 Android 不兼容的控件:

<View style={containerStyle}>
<Text style={labelStyle}>Drink:</Text>
<SegmentedControlIOS
tintColor={styleBackground}
style={{ flex: 2 }}
values={['Value1', 'Value2']}
selectedIndex={this.state.drink}
onChange={(event) => {
this.setState({ drink: event.nativeEvent.selectedSegmentIndex });
}}
/>
<View style={{ flex: 1 }} />
</View>

我想使用 React-Native-Segmented-Android库来解决这个问题。我觉得我应该能够做这样的事情:

<View style={containerStyle}>
<Text style={labelStyle}>Drink:</Text>
const Component = Platform.select({
ios: () => require('SegmentedControlIOS'),
android: () => require('react-native-segmented-android'),
})(
tintColor={styleBackground}
style={{ flex: 2 }}
values={['Value1', 'Value2']}
selectedIndex={this.state.drink}
onChange={(event) => {
this.setState({ drink: event.nativeEvent.selectedSegmentIndex });
}}
/>);
<View style={{ flex: 1 }} />
</View>

但这(也许不足为奇)不起作用。谁能指出我正确的方法?我知道我只能为 iOS/Android 使用两个不同的文件,但如果可能的话,我宁愿将它们放在一个文件中。

最佳答案

我会创建一个 sepeare 组件,这个组件会根据平台返回段,但您可以创建一个内部函数作为替代。在 render 中调用此函数来处理决定应用程序运行哪个平台并根据平台返回段。

_segmentPicker() {
if (Platform.OS == 'android') {
return (
<SegmentedControlIOS
tintColor={styleBackground}
style={{ flex: 2 }}
values={['Value1', 'Value2']}
selectedIndex={this.state.drink}
onChange={(event) => {
this.setState({ drink: event.nativeEvent.selectedSegmentIndex });
}}
/>
);
} else if (Platform.OS == 'ios') {
return (
<SegmentedControlIOS
tintColor={styleBackground}
style={{ flex: 2 }}
values={['Value1', 'Value2']}
selectedIndex={this.state.drink}
onChange={(event) => {
this.setState({ drink: event.nativeEvent.selectedSegmentIndex });
}}
/>
);
}
}


render(){
return (
<View>
{this._segmentPicker()}
.
.
</View>
);
}

关于android - React Native 中的平台特定组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com