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

时间:2016-01-12 18:44:41

标签: javascript css react-native

据我所知,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中的初学者,我在定义能够执行此操作的类时遇到了问题。任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:1)

使用spread operator

扩展现有样式定义

您可以使用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>
    );
  }
}

答案 1 :(得分:1)

尝试这样做:

button.js

export default class Button extends Component {
  render(){
    return (
      <View style={{ width:this.props.width, height: this.props.height }}>
        <Text>{this.props.text}</Text>
      </View>
    )
  }
}

然后,在您的视图中使用它:

import Button from './button'

<Button height={50} width={200} text="Hey, this is a button" />