onClick 不呈现新的react组件。

IT技术 javascript reactjs
2021-03-16 08:11:24

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

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

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

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

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

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

5个回答

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

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>
    );
  }
}
嗨,如果我只想在同一页面上加载 NewComponent 覆盖所有其他组件而不使用 react 路由器怎么办?
2021-04-17 08:11:24
onClick={()=>this._onButtonClick}
2021-04-22 08:11:24
@MustafaMuawia:不。
2021-04-26 08:11:24
@AbhirajshriWinsome:您可能正在访问值不指向组件实例this.onButtonClick的函数this
2021-04-27 08:11:24
出于某种原因,它向我显示了这个错误:TypeError: Cannot read property 'onButtonClick' of undefined
2021-05-05 08:11:24

这是一个CodePen来展示它的实际效果。

HTML

<div id="root">loading...</div>

JSX

class NewComponent extends React.Component {
  render() {
    return (
      <div {...this.props}>
        new component
      </div>
    );
  }  
}

class Button extends React.Component {
  render() {
    return (
      <button {...this.props}>
        click
      </button>
    );
  }  
}

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      clicked: false
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({
      clicked: true
    });
  }

  render() {
    return (
      <div>
        <Button onClick={this.handleClick} />
        {this.state.clicked ? <NewComponent /> : null}
      </div>
    );
  }
};

React.render(
  <App />,
  document.getElementById("root")
);
一支笔从来没有这么多帮助。我开始遇到关于 React 的条件渲染问题 :) 谢谢!
2021-04-26 08:11:24

改用: {this.state.clicked && <NewComponent />}

你可以使用withRouter()react-router-DOM当我们使用<Route path='/path' component={newComponent} />react-router-dom 传递三个props"history,location 和 match" 时,您可以在 onClick 中使用历史props的push()函数,只需将整个组件传递到withRouter()中即可:

JSX

import { withRouter } from 'react-router-dom' ;
import Button from 'buttonFolder/button.component';
const yourComponent = ({history}) => {

return (
       <Button onClick{() => history.push.('/path')}> New componentPage </Button>
)};

export default withRouter(yourComponent);

您需要设置状态以跟踪组件的可见性。默认为 false,onclick 将 state 设置为 true。在你的渲染中做一些像 {this.state.visible ? : 空值}