How can I get a html tag's value on React?

2019-07-15 03:55发布

问题:

I'm currently developing a function of the price tab by using React. The main function of these components is to let user add one of these classes price into shopping cart .The problem is how Can I get a HTML tag's html string? my sample code is

import React from 'react';
import ReactDOM from 'react-dom';

class ProductPage extends React.Component{
  let Data = {
    classA: 60,
    classB: 70,
    classC: 80
  };
  render(){
    return(
     <PriceTab priceData={Data}/>
    )
  }
}

class PriceTab extends React.Component{
    constructor(){
       super()
     this.handleClick = this.handleClick.bind(this);
     }
    handleClick(event){
       let dom = ReactDOM.findDomNode(this.refs.priceA);
       console.log(dom.value)// got undefined.
     }
    render(){
        return()
               <div>
               <ul>
                    <li ref="priceA">{this.props.priceData.classA}</li>
                    <li><button onClick={this.handleClick}>Check Out</li>
               </ul>
               <ul>
                    <li ref="priceB">{this.props.priceData.classB}</li>
                    <li><button onClick={this.handleClick}>Check Out</li>
               </ul>
               <ul>
                    <li ref="priceC">{this.props.priceData.classC}</li>
                    <li><button onClick={this.handleClick}>Check Out</li>
               </ul>
               </div>
       }
}

ReactDOM.Render(<ProductPage/> ,document.getElementById('app'));

Also are there any way to bind one button event detecting all of the values ? Many thanks for any help ...

回答1:

You cannot get the value directly from an li element as value attribute is restricted to the input fields. What you can do is bind the handleClick function with the value.

class PriceTab extends React.Component{
    constructor(){
       super()
     this.handleClick = this.handleClick.bind(this);
     }
    handleClick(value, event){
       console.log(value)   //here you will get the value of the li element
     }
    render(){
        return()
               <div>
               <ul>
                    <li ref="priceA">{this.props.priceData.classA}</li>
                    <li><button onClick={this.handleClick.bind(this, this.props.priceData.classA)}>Check Out</li>
               </ul>
               <ul>
                    <li ref="priceB">{this.props.priceData.classB}</li>
                    <li><button onClick={this.handleClick.bind(this, this.props.priceData.classB)}>Check Out</li>
               </ul>
               <ul>
                    <li ref="priceC">{this.props.priceData.classC}</li>
                    <li><button onClick={this.handleClick.bind(this, this.props.priceData.classC)}>Check Out</li>
               </ul>
               </div>
       }
    }