首页 > 解决方案 > React 组件不在 onClick 调用的函数中执行

问题描述

首先,我从 App 调用 Country 组件,传递 showCountry(CountryDetails 不会执行的地方)

const showCountry = (country) => {
    console.log(country)
    return (
      <CountryDetails country={country} />
    )
  }
...

<Countries countries={countries} filter={filter} handleClick={showCountry}/>

国家/地区列表,每个国家/地区旁边都有一个按钮以显示国家/地区详细信息

<ul>
  {toShow.map(country => <li>{country.name} <Button country={country} handleClick={handleClick}/></li>)}
</ul>

我的按钮组件,在尝试将国家/地区数据传递给事件处理程序时遇到了一些麻烦。结束了下面的解决方案(不知道这是一个好习惯)

const Button = ({ handleClick, country}) => (
  <button onClick={() => handleClick(country)}>
    show
  </button>
)

const CountryDetails = props => {
  const country = props.country
  console.log('country details..')
  return ...
}

函数 showCountry 使用传递给它的正确数据执行,但不执行 CountryDetails。

很抱歉发了很长的帖子,欢迎任何关于更好做法的反馈!

标签: javascriptreactjs

解决方案


推荐阅读