javascript - 在 React 中获取点击元素的值

标签 javascript reactjs

如何获取被点击元素的值? event.target.value显示undefined .

import React from "react";

class Home extends React.Component{
    constructor(){
        super()
        this.state = {
            products: [],
            isLoaded: false,
            value: ""
        }
        this.handleClick = this.handleClick.bind(this);
    }

   componentDidMount(){
       fetch("/home")
       .then(res => res.json())
       .then(result =>{
           return(
               this.setState({
                   products: result,
                   isLoaded: true
               })
           )                                            
       })
   }

   handleClick(event){
       console.log(event.target) //shows full element
       console.log(event.target.value) //shows undefined    
   }
   
   render(){
      if(!this.state.isLoaded){
          return(
              <h1>Loading...</h1>
          )
      }
      return <div>{this.state.products.map(elements => 
                <div 
                        key={elements.id} 
                        onClick={this.handleClick}
                        value={elements.name}    
                        >
                        {elements.name}
                </div>
                )}
                <h1>Name: {this.state.value}</h1>
            </div>;
    }
}
export default Home;

最佳答案

<div>标签没有值,您需要传递 value支持自己:

<div 
  key={elements.id} 
  onClick={() => this.handleClick(elements.name)} // Pass as parameter
  value={elements.name} // Can be removed if there's no other purpose
  >
  {elements.name}
</div>

在函数中:

handleClick(value){
   console.log(value) // this is the value
}

关于javascript - 在 React 中获取点击元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61231687/

相关文章:

javascript - React JS setState(...) : Can only update a mounted or mounting component

javascript - React 中的 insertRow() 和appendChild() 等效项

javascript - Formik 和 ReactJs : SetFieldValue from child to parent component

javascript - jquery ui 自动完成多个 "response"方法

javascript - 逗号分隔字符串的正则表达式验证

reactjs - react-highcharts 如何调用回流?

javascript - 更新 Redux 存储后,我的组件不会重新呈现

javascript - Facebook iphone 版本作为 iOS 上 safari 之外的应用程序?

javascript - 使用 Algolia instantsearch.js 有选择地使用不同的范围 slider

javascript - 如何在路由更改时卸载组件