gpt4 book ai didi

javascript - ReactJS map onClick 获取值

转载 作者:行者123 更新时间:2023-11-29 19:05:45 25 4
gpt4 key购买 nike

我是 React 的新手,我正在创建一个将使用 onClick 事件获取值的应用程序,我想我会做这样的事情:

import React, { Component } from 'react';

class Ingredients extends Component {
// Functions
clickIngredient() {
let val = this.refs.itemValue.value;
console.log(val);
}
render() {
// Print out all ingredients through mapping
// First create var from props
const ingredients = this.props.data;
// Now map through it
const ingredientList = ingredients.map((item, i) => {
// Return listitem
return (
<li key={i} ref="itemValue" value={item} onClick={this.clickIngredient.bind(this)}>{item}</li>
);
});
// Final view
return (
<div className="ingredients">
<ul className="ingredient-list">
{ingredientList}
</ul>
</div>
)
}
}

export default Ingredients;

但是我没有得到值,我做错了什么?

最佳答案

li 元素没有 value 属性。试试这个:

设置data-value 属性而不是value。通过 dataset.value 而不是 value 检索它。无需尝试设置 ref,只需使用点击事件的 target 属性即可到达 li 元素。

此外,此版本还展示了如何为每个列表项绑定(bind)一次 clickIngredient 而不是一次(感谢@Joshua Slate 的建议)。

class Ingredients extends Component {
clickIngredient = (ev) => {
let val = ev.target.dataset.value;
console.log(val);
};
render() {
// Print out all ingredients through mapping
// First create var from props
const ingredients = this.props.data;
// Now map through it
const ingredientList = ingredients.map((item, i) => {
// Return listitem
return (
<li key={i} data-value={item} onClick={this.clickIngredient}>{item}</li>
);
});
// Final view
return (
<div className="ingredients">
<ul className="ingredient-list">
{ingredientList}
</ul>
</div>
)
}
}

关于javascript - ReactJS map onClick 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43009026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com