react 请问这样定义函数可以么?怎么一直提示函数未定义

index.jsx(为什么定义showCityLayer提示未定义呢,定义成test就能使用,其余不管怎么定义都显示未定义)

import React, { Component } from "react";
import PropTypes from "prop-types";
import TopBar from "./components/TopBar";
import Slide from "./components/Slide";
import "./index.css";

export default class Home extends Component {
  showCityLayer = () => {
    console.log("show city layer");
  }
  render() {
    return (
      <div className="home">
        <TopBar city="杭州" showCityLayer={this.showCityLayer} />
        <div className="home__slide">
          <div className="home__slideWrap">
              <Slide data={[]} />
          </div>
        </div>
      </div>
    );
  }
}

Home.PropTypes = {};
import React from "react";
import PropTypes from "prop-types";
import "./TopBar.css";

const TopBar = ({ city, showCityLayer }) => {
  return (
    <div className="topBar">
      <div className="topBar__city" onClick={showCityLayer}>
        {city}
      </div>
      <div className="topBar__search" />
      <div className="topBar__scan" />
    </div>
  );
};

TopBar.PropTypes = {
  city: PropTypes.string.isRequired,
  showCityLayer: PropTypes.func.isRequired
};

export default TopBar;
阅读 2k
2 个回答

去好好学习下 js 中 this 是怎么工作了。
this.showCityLayer.bind(this)

可以通过箭头函数

()=>{this.showCityLayer()} 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题