在 props 中传递函数是未定义的

Passing a function in props is undefined

当试图将函数传递给子组件时,该函数未定义。实际上我什至不能直接在我的 class 中执行它。你会不会觉得有错别字?

class FriendsPage extends Component {
  constructor(props){
    super(props);
    this.mylog = this.mylog.bind(this);
  }
  mylog(){
        console.log("test debug");
  }
  renderItem(item) {
      return (<User friend={item} key={item.id} mylog={this.mylog}/>);
  }

class User extends Component {
  constructor(props){
    super(props);
  }
  render() {
      this.props.mylog(); // <== This is undefined
    ...
  }

工作正常。尽管如果您尝试在任何其他位置渲染 <User /> 而没有 prop 命名为 mylog,它将是未定义的。

class FriendsPage extends React.Component {
    constructor(props) {
      super(props);
      this.mylog = this.mylog.bind(this);
    }
    mylog() {
      console.log("test debug");
    }
    render() {
      return ( < User mylog = {
          this.mylog
        }
        />);
      }
    }
    class User extends React.Component {
      constructor(props) {
        super(props);
      }
      render() {
        this.props.mylog();
        return <h1 > Hello < /h1>;
      }

    }

    ReactDOM.render( < FriendsPage / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>