我是 React 世界的新手,我有这样一行:
<Button onClick={() => console.log("hello")}>Button</Button>
点击后您将在控制台上打印hello
。现在将行更改为:
<Button onClick={() => <NewComponent />}>Button</Button>
现在单击按钮,我希望呈现 NewComponent
。但事实并非如此。
我不确定,为什么会这样。请注意,我在 render
方法中有上述代码。
最佳答案
您可能希望有一个有状态组件,在单击按钮后在按钮旁边显示另一个组件。您需要做的就是跟踪按钮是否被点击:
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>
);
}
}
关于javascript - onClick 不会呈现新的 react 组件。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33840150/