【问题标题】:Rendering equal width buttons in React Native在 React Native 中渲染等宽按钮
【发布时间】:2018-03-22 17:44:11
【问题描述】:

我想连续渲染 7 个宽度相等的按钮以水平填充所有可用空间。

render() {
    return (
        <FlatList
            data={this.state.days}
            renderItem={({ item }) => <View style={styles.button}><Button title={item.getDate().toString()} /></View>}
            keyExtractor={item => item.getDate().toString()}
            horizontal={true}
            style={styles.list}
        />
    );
}

const styles = StyleSheet.create({
    list: {
        display: 'flex'
    },
    button: {
        flex: 1
    }
});

它们在一个平面列表中,包裹在一个视图中,因为我不能直接设置按钮样式。 在 HTML 页面的常规 flexbox 中,这种方法有效。

这是我在 React Native 中得到的:

也许有一些我不熟悉的平面列表行为?

【问题讨论】:

    标签: javascript react-native react-native-flexbox


    【解决方案1】:

    首先,当您在 react native 中进行样式设置时,所有内容都已在 flex 中,因此您不必这样做 display : flex

    如果您想连续渲染 7 个具有相同宽度的按钮,请确保它们都具有相同的父级。然后在每一个中使用flex:1

    在这种特殊情况下,当您在样式中将数字放在flex 前面时,当您执行flex:1 时会发生什么,它会将您的父母分成许多部分并将其交给孩子。

    所以你所有的按钮都会有 1/7 的宽度。如果您将flex:2 放在其中一种样式中,则该按钮将具有 2/7 的宽度,其余的将具有 1/7 的宽度。

    请随时要求对上述内容进行更清楚的说明。

    【讨论】:

    • 是的,我了解flex: 1 的作用。所以,在我的情况下,它应该给 &lt;View&gt; 元素宽度的 1/7。但事实并非如此。也许 Flatlist 不是 &lt;View&gt; 元素的直接父级?
    【解决方案2】:

    我遇到了同样的问题,我为每个按钮添加了视图组件封面,如下代码:

    <View style={{flexDirection:"row"}}>
        <View  style={{flex:1}}>
            <Button title="Add"  />
        </View>
        <View  style={{flex:1}}>
            <Button title="Clear"  />
        </View>
        //....
    </View>
    

    【讨论】:

      【解决方案3】:

      您是否尝试过将flex: 1 添加到列表中以占用整个水平空间?

      【讨论】:

        【解决方案4】:

        在我看来,尝试在样式对象 list 中添加 justifyContentspace-between

        【讨论】:

          【解决方案5】:

          在每个项目中,设置此样式:

          width:width/7
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-03-30
            • 1970-01-01
            • 2019-10-28
            • 2019-08-14
            • 2015-06-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多