gpt4 book ai didi

javascript - 创建可重用 - 运行时计算的样式表样式

转载 作者:太空宇宙 更新时间:2023-11-04 02:41:01 26 4
gpt4 key购买 nike

据我所知,React Native 的文档展示了样式的硬编码值。

我是一名经验丰富的 OOP,我想构建更多可重用的组件。例如,React Native 文档教您使用这种方法来设计元素:

renderButton: function() {
return (
<TouchableHighlight onPress={this._onPressButton}>
<Image
style={styles.button}
source={require('image!myButton')}
/>
</TouchableHighlight>
);
},

var styles = StyleSheet.create({
button: {
width: 80,
},
});

据我所知,如果以这种方式完成,则对于具有不同按钮组件的问题没有好的解决方案。

理想情况下,我希望能够做到这一点:

class Button extends Component {
render() {
return (
//render stuff according to passed in attributes
);
}
}

//usage
<Button width="50" height="40" onPress={this.buttonPressed}/>
<Button width="100" height="20" onPress={this.anotherButtonPressed}/>

但是,作为 JavaScript 的初学者,我在定义一个能够执行此操作的类时遇到了麻烦。任何建议表示赞赏。

最佳答案

使用扩展运算符扩展现有样式定义

您可以使用 spread operator 扩展带有一些附加定义的预定义样式.只需使用预定义样式 (...{}) 和附加样式 (styles.button) 展开一个空对象 ({width, height})。

const styles = StyleSheet.create({
button: {
backgroundColor: 'blue'
}
});

export default class Button extends Component {
render() {
const {width, height} = this.props;
// Combine the predefined styles with some additional definitions
const style = [...{}, styles.button, { width, height}]

return (
<View style={style}>
<Text>Button</Text>
</View>
);
}
}

关于javascript - 创建可重用 - 运行时计算的样式表样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34751469/

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