我想读取onClick事件值财产。但当我点击它时,我在控制台上看到类似这样的内容:
SyntheticMouseEvent {dispatchConfig: Object, dispatchMarker: ".1.1.0.2.0.0:1", nativeEvent: MouseEvent, type: "click", target
我的代码工作正常。运行时,我可以看到{column},但无法在onClick事件中获取它。
我的代码:
var HeaderRows = React.createClass({
handleSort: function(value) {
console.log(value);
},
render: function () {
var that = this;
return(
<tr>
{this.props.defaultColumns.map(function (column) {
return (
<th value={column} onClick={that.handleSort} >{column}</th>
);
})}
{this.props.externalColumns.map(function (column) {
// Multi dimension array - 0 is column name
var externalColumnName = column[0];
return ( <th>{externalColumnName}</th>);
})}
</tr>
);
}
});
如何在React js中向onClick事件传递值?
通过将count作为参数从主组件传递到子组件,实现显示对象的总计数,如下所述。
这里是MainComponent.js
import React, { Component } from "react";
import SubComp from "./subcomponent";
class App extends Component {
getTotalCount = (count) => {
this.setState({
total: this.state.total + count
})
};
state = {
total: 0
};
render() {
const someData = [
{ name: "one", count: 200 },
{ name: "two", count: 100 },
{ name: "three", count: 50 }
];
return (
<div className="App">
{someData.map((nameAndCount, i) => {
return (
<SubComp
getTotal={this.getTotalCount}
name={nameAndCount.name}
count={nameAndCount.count}
key={i}
/>
);
})}
<h1>Total Count: {this.state.total}</h1>
</div>
);
}
}
export default App;
这里是SubComp.js
import React, { Component } from 'react';
export default class SubComp extends Component {
calculateTotal = () =>{
this.props.getTotal(this.props.count);
}
render() {
return (
<div>
<p onClick={this.calculateTotal}> Name: {this.props.name} || Count: {this.props.count}</p>
</div>
)
}
};
尝试实现上述内容,您将得到传递参数如何在任何DOM方法上的reactjs中工作的确切场景。
有两种方法可以在事件处理程序中传递参数,以下是一些方法。
可以使用箭头函数环绕事件处理程序并传递参数:
<button onClick={() => this.handleClick(id)} />
上面的示例等效于调用.bind,也可以显式调用bind。
<button onClick={this.handleClick.bind(this, id)} />
除了这两种方法之外,还可以将参数传递给定义为咖喱函数的函数。
handleClick = (id) => () => {
console.log("Hello, your ticket number is", id)
};
<button onClick={this.handleClick(id)} />
这个例子可能和你的有点不同。但我可以向你保证,这是解决这个问题的最佳方案。我已经找了好几天没有性能问题的解决方案。终于想出了这个。
class HtmlComponent extends React.Component {
constructor() {
super();
this.state={
name:'MrRehman',
};
this.handleClick= this.handleClick.bind(this);
}
handleClick(event) {
const { param } = e.target.dataset;
console.log(param);
//do what you want to do with the parameter
}
render() {
return (
<div>
<h3 data-param="value what you wanted to pass" onClick={this.handleClick}>
{this.state.name}
</h3>
</div>
);
}
}
更新
如果您想处理应该作为参数的对象。您可以使用JSON.stringify(对象)将其转换为字符串并添加到数据集。
return (
<div>
<h3 data-param={JSON.stringify({name:'me'})} onClick={this.handleClick}>
{this.state.name}
</h3>
</div>
);