javascript - React event.target.value 返回未定义

标签 javascript reactjs

所以我想知道是否可以在组件中添加一个方法,以便我可以单击 h1元素重定向到相应的 target.value页面插入 onClick事件如下代码:

import React from 'react'
import CollectionItem from '../collection-item/collection-item.component'
import './collection-preview.styles.scss'
import { withRouter } from 'react-router-dom'


const CollectionPreview = ({ title, items, history }) => (
    <div className='collection-preview'>
        <h1 className='title' onClick={(event) => history.push(`/shop/${event.target.value}`)}>
            {title.toUpperCase()}
        </h1>
        <div className='preview'>
            {
                items
                    .filter((item, index) => index < 4)
                    .map((item) => (
                        <CollectionItem key={item.id} item={item} />))
            }
        </div>
    </div>
)

export default withRouter(CollectionPreview)

但是没有成功。 event.target.value总是返回undefined ,即使当我尝试控制台仅记录event.target时,它通常返回 h1我点击的元素。我该如何解决这个问题?

最佳答案

我不确定为什么你在 H1 上使用 onClick 事件。我认为您在 H1 标记内使用了链接。

import React from "react";
import CollectionItem from "../collection-item/collection-item.component";
import "./collection-preview.styles.scss";
import { withRouter, Link } from "react-router-dom";

const CollectionPreview = ({ title, items, history }) => (
  <div className="collection-preview">
  
    <h1 className="title">
      // You should use a Link component instead on the onClick props
      <Link to={`/shop/${title.toUpperCase()}`}>{title.toUpperCase()}</Link>
    </h1>
    
    <div className="preview">
      {items
        .filter((item, index) => index < 4)
        .map(item => (
          <CollectionItem key={item.id} item={item} />
        ))}
    </div>
  </div>
);

export default withRouter(CollectionPreview);

希望有帮助。 快乐编码

关于javascript - React event.target.value 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59332881/

相关文章:

javascript - 提取 Redux Store/State 作为选择器

reactjs - 如何将 React 应用程序部署到个人页面的 Github 页面

reactjs - React原生上传图片 Spring boot

javascript - (React) 动态组件条件设置状态

javascript - react : make a cycle-through component with both forward and backward directions using Generator

javascript - 输入上的 KeyPress 不起作用

javascript - Node.js - 如何检查请求数据?

javascript - 是否可以自定义 Chrome 或其他浏览器以在所有打开的选项卡上运行本地 JavaScript 文件?

javascript - 等待 setState 完成

javascript - 刷新 RxJs 主题