我在JSX中使用三元运算符根据User的选择设置的某些状态生成一些组件。我想要做的是调用JavaScript函数或一些语句以及生成组件。
这是我的相关代码:
{
this.state.isTextEditor === 'yes'
?
<Row>
<Col sm={12}>
<TextEditor placeholder="Job description here"/>
</Col>
</Row>
:
<FormGroup controlId="companySignupFormJD">
<Row>
<Col sm={12}>
<SelectFile
ref="JD-file"
image={false}
controlId={'JD-file'}
supportedFiles={supportedDocs}
btnLabel={'Select File'}
helpText={'PDF, DOC DOCX or TXT'}
onChange={::this.setJDFile} />
</Col>
</Row>
</FormGroup>
}
我想做的是这样的事情:
{
this.state.isTextEditor === 'yes'
?
<Row>
<Col sm={12}>
<TextEditor placeholder="Job description here"/>
</Col>
</Row>
(and someGlobalVariable += 'classActive')
:
...//same code as above
}
任何形式的帮助都将受到赞赏。
答案 0 :(得分:2)
如何在JSX中使用if
,详情可在此处找到
https://facebook.github.io/react/tips/if-else-in-JSX.html
这里是文档页面(上面)中的相关代码:
var loginButton;
if (loggedIn) {
loginButton = <LogoutButton />;
} else {
loginButton = <LoginButton />;
}
return (
<nav>
<Home />
{loginButton}
</nav>
);
所以在你的情况下,它将是
if(this.state.isTextEditor === 'yes'){
data = <Row>
<Col sm={12}>
<TextEditor placeholder="Job description here"/>
</Col>
</Row>;
} else {
data = <Row>
<Col sm={12}>
<TextEditor placeholder="Job description here"/>
</Col>
</Row>;
}
稍后只需添加{data}
,即应呈现jsx。
答案 1 :(得分:0)
三元运算符之所以被称为是因为它们处理了三件事。您不能在一个三元语句中分离多个操作。它们主要用于存储值或进行一次函数调用。
只需使用if/else
语句即可。无论如何,它们通常都更加清晰。