问答 百科手机端

onClick不会呈现新的react组件。

2023-05-20 11:32

您可能希望有一个状态组件,该状态组件在单击按钮之后在按钮旁边显示另一个组件。您需要做的就是跟踪按钮是否被单击:

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>
    );
  }
}

我是新来的世界,我有这样的话:

<Button onClick={() => console.log("hello")}>Button</Button>

然后单击,您将被hello打印在控制台上。现在将行更改为:

<Button onClick={() => <NewComponent />}>Button</Button>

现在点击该按钮,我希望它NewComponent会被渲染。但事实并非如此。

我不确定为什么会这样。请注意,我在render方法中有上面的代码。

热门