onClick 不呈现新的反应组件. [英] onClick doesn't render new react component.

查看:31
本文介绍了onClick 不呈现新的反应组件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是反应世界的新手,我有这样的线路:

点击你会在控制台上打印hello.现在将行更改为:

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

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

解决方案

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

class MyComponent 扩展 React.Component {构造函数(道具){超级(道具);this.state = {显示组件:假,};this._onButtonClick = this._onButtonClick.bind(this);}_onButtonClick() {this.setState({显示组件:真,});}使成为() {返回 (<div><Button onClick={this._onButtonClick}>Button</Button>{this.state.showComponent ?<新组件/>:空值}

);}}

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

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

and on click you will get hello printed on the console. Now change the line to:

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

now on click on the button, I expect the NewComponent to be rendered. But it doesn't.

I'm not sure, why that is the case. Note that I have the above code in the render method.

解决方案

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

这篇关于onClick 不呈现新的反应组件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆