有没有办法在 React JS 中使用 onClick 有条件地呈现内容?

Is there a way to conditionally render content using onClick in react JS?

有没有一种方法可以实现下面的条件渲染内容,而不是在 return 语句中使用 {renderAuthButton()},我想用 onCLick 实现 运行 renderAuthButton()?

class App extends Component {
  // ...

  render() {
    let {isLoggedIn} = this.state;

    const renderAuthButton = () => {
      if (isLoggedIn) {
        return <button>Logout</button>;
      } else {
        return <button>Login</button>;
      }
    }

    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering in React.
        </h1>
        {renderAuthButton()}
      </div>
    );
  }
}

我不是很明白你的需求,但要有条件地渲染,你可以这样做

state = {
  show: false,
}
<div className="App">
        <button onClick={() => this.setState((prev) => { show: !prev.show })}>Toggle</button>
        {this.state.show && <MyComponent />}
      </div>

我不完全确定您要做什么,但这是您在 React 中有条件地呈现内容的方式:

class App extends React.Component {
  constructor(props){
    super(props);
    
    this.state = {
      show: false
    }
    
    this.toggleShow = this.toggleShow.bind(this);
  }
  
  toggleShow(){
    this.setState({show: ! this.state.show})
  }
 
  render(){
    return (
      <div>
        <button onClick={this.toggleShow}>Filter Content</button>
        
        {this.state.show ? (
          <p>This content is conditionally shown</p>
        ) : (
          <p>The content is now hidden</p>
        )}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("root"))
<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="root"></div>