我有以下 React Native 代码:
<View>
{
a
?
(
<View/>
)
:
(
<View/>
)
}
</View>
我想在三元语句的第一个分支中创建一个变量,并认为我可以这样做:
<View>
{
a
?
{
let b = 1;
return <View/>
}
:
(
<View/>
)
}
</View>
这给我带来了以下两个 Typescript 错误,并导致应用程序崩溃:“逗号运算符的左侧未使用,没有副作用。”和“运算符 '<' 不能应用于类型 '{ return(): any; }' 和 'typeof View'”
我之前已经在 React Native 中用 {return ...}
替换了 ()
,但不明白为什么它在这里不起作用。有什么想法吗?
编辑:解决方案
问题在于,在 Javascript 的某些区域中,您可以使用 {return ...}
代替 ()
,但三元运算符不是其中之一。例如,对于像 map()
这样的数组方法,以下两段代码是等效的:
array.map(item => {return 1})
array.map(item => (1))
但以下两个不是(第一个有效,第二个抛出错误):
let a = true ? (1) : (2)
let a = true ? {return 1} : {return 2}
我的场景的解决方案是在 JSX 外部定义变量。在这种情况下:
render() {
let b = 1
return (
<View>
{
a
?
(
<View/>
)
:
(
<View/>
)
}
</View>
)
}
最佳答案
我认为您不能在大括号内使用return
。花括号的内容会自动返回给您。
例如
{ <mycomp /> }
I want to create a variable in the first branch of the ternary statement
我认为您不应该在返回对象中创建变量。变量应该在 render 方法的主体中创建。例如
render() {
const myvar = getmyvar()
return (<someel> {myvar} </someel> )
}
关于javascript - react native : How to add variables inside View?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57511685/