[英]React Native - unable to pass state variable into style
我的代码获取一个 json 文件,计算一个值,我想将此值传递到 TouchableOpacity 的样式中。 以下是我的尝试:
const [height, setHeight] = useState(0)
const [isLoading, setLoader] = useState(true)
const fetching = async () => {
...//code that fetches the value
setHeight(value)
setLoader(false)
}
if (isLoading) {
return (
<Text> Loading...</Text>
)
}
return (
<View>
<TouchableOpacity
style={{height: height, width:30, backgroundColor: "red" }} />
... //other parts of the return statement
</View>
)
完整代码:
<View style={{height: height}}>
<TouchableOpacity
style={{width:30, borderWidth:5, marginTop:20, backgroundColor:"blue", height:height}}>
</TouchableOpacity>
</View>
任何帮助,将不胜感激。
我认为你的 useState 很好。 但是,父View
没有任何空间,或者 TouchableOpacity 没有任何可显示的内容。
你可以尝试这样做:
return (
<View>
<TouchableOpacity
style={{height, width:30, borderWidth: 5 }} />
... //other parts of the return statement
</View>
)
如果看不到边框,则是父View
有问题
然后你可以尝试:
return (
<View style={{flex: 1}}>
<TouchableOpacity
style={{height, width:30, borderWidth: 5 }} />
... //other parts of the return statement
</View>
)
您还可以尝试将带有一些文本的Text
组件添加到 TouchableOpacity。
这段代码:
import React, { useEffect, useState } from 'react';
import {Text, View, TouchableOpacity} from 'react-native';
export default function App() {
const [height, setHeight] = useState(0)
const [isLoading, setLoader] = useState(true)
useEffect(() => {
const timerTask = setInterval(() => {
setHeight(Math.random() * 200)
setLoader(false);
}, 5000);
return () => clearInterval(timerTask);
}, [])
if (isLoading) {
return (
<Text> Loading...</Text>
)
}
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<TouchableOpacity
style={{width: 30, borderWidth: 5, marginTop: 20, backgroundColor: "blue", height}}>
</TouchableOpacity>
</View>
)
}
产生蓝色的可触摸不透明度,每 5 秒改变一次高度。 此外,当我触摸它时,它会变成较浅的阴影。
在我看来,您可能没有在TouchableOpacity
的渲染函数中传递style
属性, TouchableOpacity
是您自己的自定义组件,不是吗?
const TouchableOpacity = ({ style }) => {
...
return (
<div style={style} >
...
</div>
);
}
Add a height and width to your element's style
height: 50, width: '100%', backgroundColor: "#000000"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.