【问题标题】:Call a React Function from inside Render从 Render 内部调用 React 函数
【发布时间】:2016-10-23 17:12:42
【问题描述】:

我将这个 table component 与单选框(行选择(单))一起使用,我想将反应状态更新为当前选定的行。

一个名为onRowSelect 的函数显示所选行。为了更新所选行的状态,我创建了一个名为 showRow() 的函数,该函数在 onRowSelect 中调用。但是,我不断收到 this.showRow() is not a function 错误。

我在渲染函数之外使用 showRow(),因为我需要使用当前选择的行更新状态。

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>
    )
  }
}

【问题讨论】:

  • 只需将 onRowSelect 移到渲染之外,使用其他功能

标签: function reactjs render


【解决方案1】:

问题是onRowSelect 中的this 不是您期望的组件实例。

您可以对将引用组件实例的词法 this 使用 ES6 箭头函数。

所以而不是:

var selectRowProp = {
  mode: "radio",
  clickToSelect: true,
  bgColor: "#A7EC57",
  onSelect: onRowSelect
};

function onRowSelect(row, isSelected){
  this.showRow(row, isSelected);
}

你应该可以这样做:

var selectRowProp = {
  mode: "radio",
  clickToSelect: true,
  bgColor: "#A7EC57",
  onSelect: (row, isSelected) => this.showRow(row, isSelected)
};

或者甚至只是以下,因为您已经将showRow 绑定到构造函数中的组件上下文:

var selectRowProp = {
  mode: "radio",
  clickToSelect: true,
  bgColor: "#A7EC57",
  onSelect: this.showRow
};

下面是对 this 在 JavaScript 中如何工作的更多说明:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 2019-08-28
    • 2014-10-22
    • 2018-09-11
    • 2017-07-11
    • 1970-01-01
    • 2022-12-10
    • 2018-04-08
    相关资源
    最近更新 更多