为什么onClick会在组件渲染时触发,而不是在单击时触发?

Use*_*ame 5 reactjs react-jsx

我有这个按钮console.log作为测试,每当我刷新页面而不是单击导航按钮时它都会被触发.如果您需要更多,请告诉我您是否可以看到此代码的问题.

import React from 'react';
import SideNav from "react-sidenav";
var TeamActions = require('../actions/TeamActions');

export default class Nav extends React.Component {
  pushName(name) {
    TeamActions.setTeamName(name);
  }

  render() {
    return(
      <SideNav.Menu
        path="#"
        itemHeight="32px"
        styles={{margin: "0"}}
      >
        <SideNav.MenuItem
          itemKey="truck"
        >
        //this is where I'm using onClick
          <SideNav.ILeftItem
            className="fa fa-truck"
            onClick={console.log("hello")}
          >
              Boston Celtics
          </SideNav.ILeftItem>
        </SideNav.MenuItem>
Run Code Online (Sandbox Code Playgroud)

Jed*_*rds 8

那是因为您实际上是console.log在onClick处理程序中调用该函数,而不是仅仅指向它的引用.JSX编译为纯JS,因此{}将评估括号之间的任何内容.您只需指向onClick中的函数引用,而不是调用它.

它有点复杂,因为当使用ES6类时你需要绑定到当前this,它不是自动编码你喜欢旧样式React.createClass语法,但这是一个简单的例子,

class MyComponent {

  onLinkClicked () {
    console.log('Clicked!')
  }

  render () {
    return (
      <a onClick={this.onLinkClicked.bind(this)}>Click me</a>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)