简体   繁体   English

如何从中获取价值<li>标签

[英]How to get value from <li> tag

I'm a beginner in React.js and need some help.我是 React.js 的初学者,需要一些帮助。 I want to get the value or data from a <li> -tag when you click on it.当你点击它时,我想从<li>标签中获取值或数据。 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>
 );
}
...

You're getting undefined because target.value is only used for form elements such as input .你得到undefined因为target.value仅用于表单元素,例如input

You can pass the function a unique identifier, which you then can use to fetch it's value from this.state .您可以向该函数传递一个唯一标识符,然后您可以使用该标识符从this.state获取它的值。

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.最大的问题可能取决于此元素的值是否可以在 DOM 中更改,或者是否始终保持静态。

Here are my proposed solutions for both:以下是我为两者提出的解决方案:


Element can change value in DOM:元素可以改变 DOM 中的值:

If you want to update the value of your li element, you can do this:如果要更新li元素的值,可以执行以下操作:

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 is an array that is in the components constructor and contains the initial values for each element. this.state.data是一个位于组件构造函数中的数组,包含每个元素的初始值。 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.当您单击一个元素时,您将调用clickOnMe函数并传入一个参数,该参数对应于当前元素数据所在的数组中的索引。

If you want to change this value later, you can call changeData with the value and index as parameters.如果以后要更改此值,可以使用值和索引作为参数调用changeData Make a copy of the entire array, change the value in said index, then update the state .复制整个数组,更改所述索引中的值,然后更新state


Element is static in DOM:元素在 DOM 中是静态的:

If the value of li is always static, then you can do:如果li的值总是静态的,那么你可以这样做:

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.在这里你可以直接绑定哪个值对应于所述元素,然后在函数中用它做你想做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM