【问题标题】:React native in styles if expression反应原生风格 if 表达
【发布时间】:2020-08-15 11:56:34
【问题描述】:

我在 Touchableopacity 中列出数据。列表项长度在 10-350 个字符之间。每个列表项都像框一样有边框,它们的高度是静态的(150 像素)。我只想做的就是让高度动态化。 这就是我尝试过的。

样式

listItem:{
    flex: 1,
    width: '100%',
    height: 150,
    backgroundColor:'#E7C287',
    borderWidth: 1,  
    justifyContent: 'center',
    alignItems: 'center',  
        },    
listItem2:{
    flex: 1,
    width: '100%',
    height: 150,
    backgroundColor:'#E7C287',
    borderWidth: 1,  
    justifyContent: 'center',
    alignItems: 'center',  
        },    

我的解决办法是

      { Object.keys(text).length <200 ?
          
           <View
     
           style={listStyles.listItem}>
           
             
         <Text         
           style={ fontstill}
            
             
             >{text}</Text>
         </View>
        
       :
      
       <View
     
        style={listStyles.listItem2}>
        
          
      <Text         
        style={ fontstill}
         
          
          >{text}</Text>
      </View>
       }
    </TouchableOpacity>

我怎样才能做到像 listStyles.listItem3这样的3个条件

【问题讨论】:

  • 你在写style={时已经打开了一个js块,所以你应该从计数中删除花括号sytle={[ count &lt; 250 ? .....]}
  • 是的,正如我所提到的,我试过了。它说的一样
  • 我不习惯使用数组语法:p,试试style={count &lt; 250 ? style1 : style2}
  • 是的,我在搜索中找到它,也是这样说的
  • 是的,但不是在文本中声明计数,您可以在声明文本之后立即声明它

标签: react-native


【解决方案1】:

尝试将您的 Text JSX 替换为

    <Text 
      //There is the I want to make it dynamic
      style={Object.keys(text).length} < 250 ? listStyles.listItem : listStyles.listItem2}>      
      {text}</Text>

【讨论】:

  • 我添加到底部
  • 去掉“250”后的“}”字符
  • 对不起,我弄错了。我已经用更改更新了答案(只是删除了额外的 {})
【解决方案2】:

你应该把变量的声明和jsx分开

import React from 'react';
import { listStyles } from './styles/ListStyles';

const [stil, setstil] = useState(listStyles.listItem);

const text = item1.sample;

const ListStyles = () => {
  const count = Object.keys(text).length;
  return (
    <TouchableOpacity
        <View style={stil}>
          <Text 
            style={count < 250 
            ? listStyles.listItem 
            : listStyles.listItem2
            }>
              {text}
            </Text>
      </View>
    </TouchableOpacity>
  );
}

【讨论】:

  • 仍然找不到,我提出了一个解决方案,但它适用于 2 个条件。我怎样才能做到 3
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
相关资源
最近更新 更多