传递道具中的函数是不确定的

时间:2017-03-01 08:54:06

标签: javascript react-native react-native-android

尝试将函数传递给子组件时,该函数未定义。实际上我甚至不能直接在我班上执行它。你认为会有拼写错误吗?

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
    ...
  }

1 个答案:

答案 0 :(得分:0)

工作正常。但是,如果您尝试在任何其他位置呈现<User /> prop名为mylog的{​​{1}},那么它将是未定义的。

&#13;
&#13;
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'));
&#13;
<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>
&#13;
&#13;
&#13;