簡體   English   中英

如何在 React.Component.render() 中使用要渲染的部分 jsx 組件?

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

我是新人反應。 我想在主 React.Component.render() 中包含一個部分 JSX 塊,如下所示:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM