Reactjs 是否允许使用js添加react jsx代码块?
我有一个简单的渲染函数,有一些条件Reactjs 是否允许使用js添加react jsx代码块?,reactjs,react-native,Reactjs,React Native,我有一个简单的渲染函数,有一些条件 class AwesomeTestClass { constructor() { /* constructor stuff */ } reder() { let OUT = (<Text> basic text 1 </Text>); if (someCondition) { OUT += (<Text> add some condition text </Text>);
class AwesomeTestClass {
constructor() { /* constructor stuff */ }
reder() {
let OUT = (<Text> basic text 1 </Text>);
if (someCondition) {
OUT += (<Text> add some condition text </Text>);
} else {
OUT += (<Text> add other condition text </Text>);
}
OUT += (<Text> end of awesome text </Text>);
return (
<View>
{OUT}
</View>
);
}
}
错误输出:
RawText“[object object][object]”
必须包装在显式的
组件中
let OUT = "<Text>Awe</Text>";
OUT = OUT + "<Text>some</Text>";
let OUT = "<Text>Awe</Text>";
OUT += "<Text>some</Text>";
错误输出:
RawText“[object object]some”
必须包装在显式的
组件中
我不想把每条语句都移动到一个函数中。也许只是使用一种条件呈现策略,我会提出如下建议:
return (
<View>
{ someCondition ?
(<Text> add some condition text </Text>):
(<Text> add other condition text </Text>)
}
<Text> end of awesome text </Text>
</View>
);
返回(
{某个条件?
(添加一些条件文本):
(添加其他条件文本)
}
精彩文本的结尾
);
查看:您可以将组件推入阵列并渲染:
render() {
let OUT = [(<Text key={1}> basic text 1 </Text>)];
if (someCondition) {
OUT.push(<Text key={2}> add some condition text </Text>);
} else {
OUT.push(<Text key={3}> add other condition text </Text>);
}
OUT.push(<Text key={4}> end of awesome text </Text>);
return (
<View>
{OUT}
</View>
);
}
render(){
释放=[(基本文本1)];
如果(某些条件){
OUT.push(添加一些条件文本);
}否则{
OUT.push(添加其他条件文本);
}
OUT.push(文本结束);
返回(
{OUT}
);
}
注意,我在本例中添加了一个硬编码密钥。如果使用循环渲染这些项,则需要一个键,以便react可以区分动态添加或删除的每个组件。不要使用索引作为键。Awesome我使用了数组方法,尝试添加每个组件并渲染它。但是我可以只渲染数组。@RensvWalstijn使用条件渲染,您不需要密钥。除非您的阵列是真正动态的(例如,从服务器读取的项目阵列),否则这不是最佳的react解决方案。或者创建一个字符串数组,然后
将字符串数组映射到中的
组件呈现@Sulthan No中的
组件,其中包含一个简单的示例。
let OUT = String(<Text>Awe</Text>);
OUT = OUT + String(<Text>some</Text>);
let OUT = String(<Text>Awe</Text>);
OUT += String(<Text>some</Text>);
let OUT = String(<Text>Awe</Text>);
OUT = OUT + "<Text>some</Text>";
let OUT = String(<Text>Awe</Text>);
OUT += "<Text>some</Text>";
return (
<View>
{ someCondition ?
(<Text> add some condition text </Text>):
(<Text> add other condition text </Text>)
}
<Text> end of awesome text </Text>
</View>
);
render() {
let OUT = [(<Text key={1}> basic text 1 </Text>)];
if (someCondition) {
OUT.push(<Text key={2}> add some condition text </Text>);
} else {
OUT.push(<Text key={3}> add other condition text </Text>);
}
OUT.push(<Text key={4}> end of awesome text </Text>);
return (
<View>
{OUT}
</View>
);
}