ReactJS map onClick获取值

时间:2017-03-24 20:57:38

标签: javascript reactjs

我是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;

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

2 个答案:

答案 0 :(得分:2)

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

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

此外,此版本还显示如何为每个列表项绑定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>
      )
    }
}

答案 1 :(得分:1)

我想知道为什么你没有将值作为参数传递给函数。 喜欢:onClick={this.clickIngredient.bind(this,item)}

解决方案:

import React, { Component } from 'react';

class Ingredients extends Component {
// Functions
clickIngredient(value) {
let val = 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)}>{item}</li>
  );
});
// Final view
return (
  <div className="ingredients">
    <ul className="ingredient-list">
      {ingredientList}
    </ul>
  </div>
  )
 }
}

export default Ingredients;