链接组件上的OnClick事件

时间:2019-04-15 09:40:55

标签: reactjs

我的页面上有几个NavLink,我需要使用被点击的NavLink的名称设置父级的状态,如果NavLink不存在,该怎么办?没有OnClick`事件?

我想做这样的事情:

<Tile to="./request" department={item.catName} key={item.id} 
      onClick={() => this.setState(catId: item.id)} />

但是onClick似乎没有被解雇。

export default class extends Component {
  state = {
  };

  componentDidMount() {
    this.props.handleChange(this.state);
  }

  componentDidUpdate(_, prevState) {
     if (this.state !== prevState) {
        this.props.handleChange(this.state);
     }
  }

  render() {
    const { categoriesWithSub } = this.props.categoriesWithSub;
    return (
        {categoriesWithSub &&
          categoriesWithSub.map(item => (
            <Tile
              to="./request"
              department={item.catName}
              key={item.id}
            />
          ))}
      </div>
    );
  }
}

export function Tile({ to, department, onClick }) {
  return (
    <NavLink to={to} css={tile} onClick={onClick}>
      {department}
    </NavLink>
  );
}

1 个答案:

答案 0 :(得分:2)

导航链接需要从您的自定义组件瓷砖

传递的 onClick

将导出功能更改为

export function Tile({ to, department, onClick }) {
  return (
    <NavLink to={to} css={tile} onClick={onClick}>
      {department}
    </NavLink>
  );
}