我是新来的反应世界,我有这样的行:
- <Button onClick={() => console.log("hello")}>Button</Button>
点击后,您将在控制台上打印出来.现在更改行:
- <Button onClick={() => <NewComponent />}>Button</Button>
现在点击按钮,我希望渲染NewComponent.但是没有.
解决方法
您可能希望有一个有状态的组件在单击按钮后显示该按钮旁边的另一个组件.所有您需要做的是跟踪按钮是否被点击:
- 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>
- );
- }
- }