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

标签 javascript react-native

当试图将函数传递给子组件时,该函数未定义。实际上我什至不能直接在我的类里面执行它。你会认为有错字吗?

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>

关于javascript - 在 props 中传递函数是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42527211/

相关文章:

javascript - 如何用 express 发送102处理?

react-native - 启动应用程序时出现世博会错误。 "ApiV2Error: Account not found. "

react-native - 如何使用expo github actions?

react-native - 不存在捆绑 URL( native react )

javascript - React Native Android FlatList onScroll 动画

javascript - .click 不注册更改的类

javascript - 如何使用cookie保存页面状态)?

javascript - 如何使用带有 razor (cshtml) 的 javascript 函数显示 html 代码?

javascript - 当 Controller $scope 变量更改时,AngularJS View 未更新?

javascript - 包的开发人员警告 * 无法在 channel "fcm_fallback_notification_channel"上发布通知 更多详细信息,请参阅日志