我目前正在使用React开发价格标签的功能。这些组件的主要功能是让用户将其中一个类别的价格添加到购物车中。问题是如何获取HTML标签的html字符串? 我的示例代码是
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'));
还有什么方法可以绑定一个检测所有值的按钮事件? 非常感谢任何帮助...
答案 0 :(得分:0)
您无法直接从li
元素获取值,因为value
属性仅限于input
字段。你可以做的是将handleClick函数与值绑定。
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>
}
}