我试图通过从输入获得的状态帮助加载组件二或三。我知道如何在渲染函数中使用三元运算符。是这样的如何在渲染函数内使用if进行比较
render: function(){
return(<div>
{this.state.in===2?<Two/>: <Three/>}
</div>
)}
但这只会工作两个比较,如果我有十个组件,并希望在10种不同的选择,加载10个不同的组件。如果我去了。这是我的尝试。我无法保留内部条件{}就像我使用三元运算符一样,如果我没有将它们保存在{}中,则渲染会将其加载为正常文本。 这里是我的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React</title>
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/jsx">
var One = React.createClass({
getInitialState: function(){
return {in:2}
},
handler: function(eve){
this.setState({
in: eve.target.value
})
},
render: function(){
return(
<div>
<input value={this.state.in} onChange={this.handler} />
if(this.state.in ===2){
<Two/>
}
if(this.state.in ===3){
<Three />
}
</div>
)
}
});
var Two = React.createClass({
render: function(){
return(<div>
This is component 2
</div>)
}
});
var Three = React.createClass({
render: function(){
return(<div>This is the third one</div>)
}
})
React.render(<One/>,document.getElementById('example'));
</script>
</body>
</html>
PS:更多的阅读和官方的文档,看看这个http://facebook.github.io/react/tips/if-else-in-JSX.html
修改组件阵列作为 作为回报{组件[this.state.in]},如果你给<>它呈现为HTML,{}用于指定JSX。我接受了你的解决方案,因为它很容易阅读 –
gates
我没有React的经验,这是一个更好的解决你的问题的JS想法。很高兴你有更好的方式来展示它。 ;-) –
哈哈,没有反应经验的人似乎在摇摆它。虽然我正在全职工作* facepalm * – gates