onClick不会呈现新的反应组件。 [英] onClick doesn't render new react component.
本文介绍了onClick不会呈现新的反应组件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的反应世界,我有这样的行:
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>
现在单击按钮,我希望 NewComponent
要渲染。但事实并非如此。
now on click on the button, I expect the NewComponent
to be rendered. But it doesn't.
我不确定,为什么会这样。请注意,我在 render
方法中有上述代码。
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屋!
查看全文