【问题标题】:Dynamic positioning of a React JSX buttonReact JSX 按钮的动态定位
【发布时间】:2019-01-13 06:54:48
【问题描述】:

我正在使用 React,我需要这样放置这个按钮:

但我有一个大问题,因为我被禁止使用边距或其他形式的位置,我有 px 或 rem 的值,基本上是静态位置。现在,我有这个代码

<div style={{ float: 'right' }}>
      <ActionButton style={{
        display : 'flex', 
        flex : '1',
        flexDirection: 'row',
        alignItems : 'center', 
        justifyContent : 'center',
        height: '40px',
        width: '151px',

      }} name={<div style = {{
        display : 'flex',
        flex : '2',
      backgroundColor : 'red', 
      float : 'right'
    }}>FILTRAR</div>} 
      icon={<div style = {{
        display : 'flex',
        flex : '2',
      backgroundColor : 'blue',
      width: '24px',
      height: '24px',
      float : 'left'}}><FilterIcon/></div>}>
      </ActionButton>
    </div>

现在我的按钮是这样的

【问题讨论】:

  • 最好设置 repl.it 或其他 react-native 沙箱,这样我们就可以对其进行实时测试。否则,这更像是一个猜测:) 查看我的答案
  • 第二张截图的代码是什么?现在他们的高度看起来相等,似乎更接近解决方案
  • 我不知道这样做...我将代码放在问题中,感谢您的帮助
  • 不过,最好上传所有代码,而不是截图 :) 无论如何,我用styled-components 更新了我的第二个沙箱,尝试通过将你的真实代码添加到这个沙箱步骤来玩它一步一步,希望你能解决你的问题。

标签: javascript html css reactjs react-native


【解决方案1】:

您可以使用百分比(即:50%)的边距,然后使用百分比转换(即:transform: translateX(-50%))来调整位置。如果您可以提供静态样式的 html,我可以生成给你的例子。

【讨论】:

    【解决方案2】:

    父样式应该已经将子样式(名称和图标)对齐到中心,而不是顶部。是的,不需要定位样式,除非孩子本身有硬编码的高度/边距值。

    由于ActionButton 的实现,可能会破坏期望的行为。

    无论如何,我对解决这个问题的建议:

    1. 使用flex-direction: 'row-reverse' 而不是floats;
    2. 从子元素中删除display: 'flex'

    这是一个简单的 web https://codesandbox.io/s/62nynm1wzk 的工作示例,希望它可以帮助您入门。

    更新:这里是一个使用button而不是div作为容器的示例,因为它更接近原始标记:https://codesandbox.io/s/y7q1vlwkwj

    【讨论】:

    • 我确实像你说的那样,我理解你的代码但没有工作
    • } name={
      Filtros
      } >
  • 结果还是和你的问题一样?如果是这样,请尝试逐个替换组件:将 parent 替换为纯 div 并将图标和文本呈现为子项
  • 我把结果放在问题里
  • 但是在组件中还是在actionbutton中?
  • 【解决方案3】:

    尝试删除 name 和 icon 属性中的 flexdisplay 样式属性,如下所示并检查它。因为 flex:2 会改变等间距子元素的宽度。

    <div style={{ float: 'right' }}>
          <ActionButton style={{
            display : 'flex', 
            flex : '1',
            flexDirection: 'row',
            alignItems : 'center', 
            justifyContent : 'center',
            height: '40px',
            width: '151px',
    
          }} name={<div style = {{
          backgroundColor : 'red', 
          float : 'right'
        }}>FILTRAR</div>} 
          icon={<div style = {{
          backgroundColor : 'blue',
          width: '24px',
          height: '24px',
          float : 'left'}}><FilterIcon/></div>}>
          </ActionButton>
        </div>
    

    【讨论】:

      猜你喜欢
      • 2016-08-09
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2016-04-19
      • 1970-01-01
      • 2015-05-04
      相关资源
      最近更新 更多