所以我想知道是否可以在组件中添加一个方法,以便我可以单击 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/