Return XML 以及在 React.js 中使用三元运算符调用 JavaScript 函数

Return XML as well call a JavaScript function using ternary operator in React.js

我在 JSX 中使用三元运算符根据用户选择设置的某些状态生成一些组件。我想要做的是在生成组件的同时调用一个 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
}

我们将不胜感激。

之所以叫三元运算符,是因为它们处理三件事。您不能在一个三元语句中分拆多个操作。它们主要用于存储值或进行一次函数调用。

只需使用 if/else 语句。无论如何,他们通常更清醒。

如何在 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。