如何在 React.Component.render() 中使用部分 jsx 组件进行渲染?

How to use a partial jsx component to be rendered in React.Component.render()?

我是react新人。我想将部分 JSX 块包含到主 React.Component.render() 中,如下所示:

showWarning(){
    if (this.state.warning)
    return <h2>Warning ! Please hide this thing by clicking below</h2>
    else
    return null
  }
  render() {
    const shouldShow = this.showWarning() //Fetching a conditional part
    return (
      <>
      shouldShow  //The part fetched above should be added here
      <input
        type="submit"
        value={this.state.warning ? "Hide" : "Show"}
        onClick={this.toggleWarn}
      />
      </>
    );
  }

我知道解决这个问题的一种方法是这样的,但这会导致复制 <input>:

if (this.state.warning) 
      return (
        <>
          <h2>Warning ! Please hide this thing by clicking below</h2>
          <input
            type="submit"
            value={this.state.warning ? "Hide" : "Show"}
            onClick={this.toggleWarn}
          />
        </>
      );
else return (
      <input
        type="submit"
        value={this.state.warning ? "Hide" : "Show"}
        onClick={this.toggleWarn}
      />
    );
  }

有什么解决办法吗?

您可以这样更新:

return (
      <>
      {this.state.warning && <h2>Warning ! Please hide this thing by clicking below</h2> }
      <input
        type="submit"
        value={this.state.warning ? "Hide" : "Show"}
        onClick={this.toggleWarn}
      />
      </>
    );

你可以使用三元运算符做这样的事情

return (
  <>
     {this.state.warning ? <h2>Warning ! Please hide this thing by clicking below</h2>: null}
      <input
        type="submit"
        value={this.state.warning ? "Hide" : "Show"}
        onClick={this.toggleWarn}
      />
  </>
)

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      warning: false
    }
  }
  
  onToggle = () => {
    this.setState(oldState => ({
      warning: !oldState.warning
    }));
  }
  
  getSomeConditionalJSX = () => {
    return this.state.warning ? <p>Conditional JSX - true</p>: <p>Conditional JSX - false</p>
  }
  
  getSomeOtherConditionalJSX = () => {
    return !this.state.warning ? <p>Other Conditional JSX - true</p>: <p>Other Conditional JSX - false</p>
  }
  
  render() {
    return (
      <React.Fragment>
       {/* {this.state.warning ? <h2> Warning!! </h2>: null} */}
        {this.getSomeConditionalJSX()}
        <input />
        {this.getSomeOtherConditionalJSX()}
        <button onClick={this.onToggle}>Toggle Warning</button>
      </React.Fragment>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="react"></div>