Call a React Function from inside Render

别说谁变了你拦得住时间么 提交于 2019-12-11 19:27:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!