【问题标题】:Creating reusable - runtime calculated StyleSheet styles创建可重用 - 运行时计算的 StyleSheet 样式
【发布时间】:2016-01-12 18:44:41
【问题描述】:

据我所知,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 的初学者,我很难定义一个能够执行此操作的类。任何建议表示赞赏。

【问题讨论】:

  • 你的意思是暗示有一个名为“组件”的 React Native 类吗?或者您想同时创建一个组件和一个按钮类?

标签: javascript css react-native


【解决方案1】:

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

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

【讨论】:

  • 看起来有点陌生(由于我对 js 不熟悉),但你从道具中获取高度/宽度的想法正是我想要的。我不清楚const {width, height} = this.props 的工作方式,以及const style 的工作方式。
  • const{width, height} = this.props 只是 `const width = this.props.width' 的简写,...使用 destructuring assignment
  • 是的,现在测试一下。感谢您的澄清
  • 那么这个答案最终能解决你的问题吗?
  • 嘿,是的!扩展运算符有点令人困惑,但我设法让我的代码有所作为。这可以满足我的需求。
【解决方案2】:

尝试这样做:

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" />

【讨论】:

  • 再次感谢纳德,介意您解释一下export default 与没有它的区别吗?另外,来自 OOP 背景,我对styles 如何访问this.props.width 有点困惑。我的印象是props 就像一个类的实例变量的字典。
  • 抱歉,我犯了一个错误并在测试后编辑了我的答案。 this.props 在组件声明之外不可用。
  • 导出默认是es6/es2015 Class定义方式声明react组件。你可以很容易地说 React.createClass({)} (es5) 并得到同样的东西!向下传递给组件的任何内容都将作为组件中的 this.props 可用,高度、宽度和文本可用的方式(甚至函数,通常也作为 props 向下传递)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 1970-01-01
相关资源
最近更新 更多