问题
I'm using this table component with radioboxes (Row selection(Single)) and I want to update the react state to the currently selected row.
A function called onRowSelect shows the row selected. To update the state to the row selected, I created a function called showRow(), which is called in onRowSelect. However, I keep getting a this.showRow() is not a function error.
I'm using showRow() outside the render function because I need to update the state with the currently chosen row.
class ChooseRowExample extends Component {
constructor(props) {
super(props);
this.state =({
chosenRow:""
});
this.showRow = this.showRow.bind(this);
}
showRow(row, isSelected){
console.log(row);
//update state here
}
render() {
var selectRowProp = {
mode: "radio",
clickToSelect: true,
bgColor: "#A7EC57",
onSelect: onRowSelect
};
function onRowSelect(row, isSelected){
this.showRow(row, isSelected);
}
return (
<div>
<BootstrapTable data={person} search={true} selectRow={selectRowProp}>
<TableHeaderColumn dataField="id" isKey={true}>Client #</TableHeaderColumn>
<TableHeaderColumn dataField="name">Company</TableHeaderColumn>
<TableHeaderColumn dataField="contact_name">Client Name</TableHeaderColumn>
</BootstrapTable>
</div>
)
}
}
回答1:
The problem is that this
within onRowSelect
is not the instance of the component like you are expecting.
You can use an ES6 arrow function for a lexical this
that will reference the component instance.
So instead of:
var selectRowProp = {
mode: "radio",
clickToSelect: true,
bgColor: "#A7EC57",
onSelect: onRowSelect
};
function onRowSelect(row, isSelected){
this.showRow(row, isSelected);
}
You should be able to do this:
var selectRowProp = {
mode: "radio",
clickToSelect: true,
bgColor: "#A7EC57",
onSelect: (row, isSelected) => this.showRow(row, isSelected)
};
Or even simply the following as you have already bound showRow
to the components context in the constructor :
var selectRowProp = {
mode: "radio",
clickToSelect: true,
bgColor: "#A7EC57",
onSelect: this.showRow
};
Here is a bit more of an expanation of how this
works in JavaScript: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this
来源:https://stackoverflow.com/questions/37956540/call-a-react-function-from-inside-render