【问题标题】:React native flexbox: set grow factor to generic presentational componentReact native flexbox:将增长因子设置为通用表示组件
【发布时间】:2018-12-24 10:09:30
【问题描述】:

React 场景中,通用 App 容器包含一个名为 Row 的表示组件,我们如何指示后者两次 -使用 flexbox 与其兄弟 View 一样大?

export default class App extends Component<Props> {
  render() {
    return (
      <View style={{flex: 1}}>
        <View style={{flex: 1}} />
        <Row style={{flex: 2}} />
      </View>
    );
  }
}

这就是 Row 组件的样子,它再次在父元素上使用 flexbox 来利用所有可用空间:

export default function Row(props: Props){
  return (
    <View style={{flex: 1}}>
      //some more children flex items
    </View>
  )
};

上面的例子不会给出预期的结果,因为 flex 样式从 App 组件({flex: 2}) 被从展示组件本身分配的样式覆盖。

制作一个 flex 展示组件的最佳实践是什么?

【问题讨论】:

    标签: react-native flexbox components


    【解决方案1】:

    您对 flexbox 的理解是正确的,问题是您没有将{{flex: 2}} 正确传递给Row 组件。

    这一行中的&lt;Row style={{flex: 2}} /&gt; 样式道具只是传递给您的Row 组件的道具,您没有使用它,所以它没有被应用。

    试试下面的

    export default class App extends Component<Props> {
      render() {
        return (
          <View style={{flex: 1}}>
            <View style={{flex: 1}} />
            <Row style={{flex: 2}} />
          </View>
        );
      }
    }
    
    
    export default function Row(props: Props){
      const { style } = props;
      return (
        <View style={[{backgroundColor: 'green'}, style]}>
          //some more children flex items
        </View>
      )
    };
    

    正如您在Row 中看到的组件样式props 被传递给View 我添加了backgroundColor: green 作为组件自己样式的示例,然后style props 是来自组件props 的样式,这个应该工作。

    回顾style prop 只能传递给react-native 组件而不是您的自定义组件,为了能够像您的示例一样使用style,您只需将该样式传递给react-native @987654333像上面的代码一样自己@。

    【讨论】:

    • 这是您推荐的吗?或者更喜欢例如在元素上将 flex="2" 设置为自己的道具?
    • 不,因为这是一种样式,最好传递样式对象...因为您以后可能需要添加更多样式...我个人认为传递样式对象比您的示例更好,除非 Row 是您想​​要以这种方式自定义的特定于布局的组件
    猜你喜欢
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2011-12-01
    • 2021-03-21
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多