如何从< li>获得价值标签 [英] How to get value from <li> tag

查看:64
本文介绍了如何从< li>获得价值标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React.js的初学者,需要一些帮助。
当我单击它时,我想从< li> -标记获取值或数据。我怎样才能做到这一点?

I'm a beginner in React.js and need some help. I want to get the value or data from a <li>-tag when you click on it. How can I do that?

...
clickOnMe : function () {
   this.setState({myData : event.target.value});
}

render : function (){
   return (
   <div>
     <ul>
        <li value="Point" onClick={this.clickOnMe}>Point</li>
     </ul>
   </div>
 );
}
...


推荐答案

您将得到未定义,因为 target.value 仅用于之类的表单元素输入

You're getting undefined because target.value is only used for form elements such as input.

您可以向函数传递一个唯一标识符,然后可以使用该标识符从 this.state获取其值

You can pass the function a unique identifier, which you then can use to fetch it's value from this.state.

实施可能会有很大不同。最大的问题可能取决于此元素的值是否可以在DOM中更改,或者是否始终保持静态。

Implementations may vary a lot. The biggest question would probably depend on whether or not the value of this element can change in the DOM, or if will remain static at all times.

以下是我为这两种方法提出的解决方案:

Here are my proposed solutions for both:

如果要更新 li 元素,您可以执行以下操作:

If you want to update the value of your li element, you can do this:

getInitialState: function() {
  return {
    data: ["point1", "point2", "point3"];
  };
}

clickOnMe = (id) => {
   console.log(this.state.data[id]);
}

changeData = (id, value) => {
   let temp = this.state.data.slice();
   temp[id] = value;
   this.setState({temp});
}

render = () => {
   return (
   <div>
     <ul>
        <li value={this.state.data[0]} onClick={this.clickOnMe.bind(this, 0)}>Point</li>
     </ul>
   </div>
 );
}

this.state.data 是组件构造函数中的数组,其中包含每个元素的初始值。单击元素时,将调用 clickOnMe 函数,并传入与当前元素数据所在的数组中的索引对应的参数。

this.state.data is an array that is in the components constructor and contains the initial values for each element. When you click on an element, you'd call the clickOnMe function and pass in a parameter that corresponds to the index in the array in which the data for the current element is.

如果以后要更改此值,可以使用值和索引作为参数调用 changeData 。复制整个数组,更改所述索引中的值,然后更新状态

If you want to change this value later, you can call changeData with the value and index as parameters. Make a copy of the entire array, change the value in said index, then update the state.

如果 li 的值始终是静态的,则可以执行以下操作:

If the value of li is always static, then you can do:

clickOnMe = (val) => {
   this.setState({myData : val});
}

render = () => {
   return (
   <div>
     <ul>
        <li onClick={this.clickOnMe.bind(this, "Point")}>Point</li>
     </ul>
   </div>
 );
}

如果您希望事物是静态的,则事情要简单得多。在这里,您可以直接绑定与所述元素对应的值,然后在函数中执行所需的操作。

If you want things to be static, things are much simpler. Here you can just directly bind which value corresponds to said element, and then in the function do what you want with it.

这篇关于如何从&lt; li&gt;获得价值标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆