onClick doesn't render new react component.

前端 未结 4 1345
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 17:37

I\'m new to react world and I have line like this:


and on cli

相关标签:
4条回答
  • 2020-11-27 18:20

    Here's a CodePen to show it in action.

    HTML

    <div id="root">loading...</div>
    

    JSX

    class NewComponent extends React.Component {
      render() {
        return (
          <div {...this.props}>
            new component
          </div>
        );
      }  
    }
    
    class Button extends React.Component {
      render() {
        return (
          <button {...this.props}>
            click
          </button>
        );
      }  
    }
    
    class App extends React.Component {
      constructor() {
        super();
    
        this.state = {
          clicked: false
        };
    
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick() {
        this.setState({
          clicked: true
        });
      }
    
      render() {
        return (
          <div>
            <Button onClick={this.handleClick} />
            {this.state.clicked ? <NewComponent /> : null}
          </div>
        );
      }
    };
    
    React.render(
      <App />,
      document.getElementById("root")
    );
    
    0 讨论(0)
  • 2020-11-27 18:24

    You need to set state to track visibility of the component. Default it to false, and onclick set state to true. In your render do something like {this.state.visible ? : null}

    0 讨论(0)
  • 2020-11-27 18:36

    Use instead: {this.state.clicked && <NewComponent />}

    0 讨论(0)
  • 2020-11-27 18:43

    You probably want to have a stateful component that shows the other component next to the button after it was clicked. All you need to do is track whether the button was clicked:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          showComponent: false,
        };
        this._onButtonClick = this._onButtonClick.bind(this);
      }
    
      _onButtonClick() {
        this.setState({
          showComponent: true,
        });
      }
    
      render() {
        return (
          <div>
            <Button onClick={this._onButtonClick}>Button</Button>
            {this.state.showComponent ?
               <NewComponent /> :
               null
            }
          </div>
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题