【问题标题】:Access props outside class在课外访问道具
【发布时间】:2016-10-03 13:28:28
【问题描述】:

我正在使用 react-bootstrap-table 并启用了 cellEdit。编辑单元格后,可以在react-bootstrap-table 中使用回调函数。我将回调函数命名为onAfterSaveCell。表中更新的行将保存到名为row 的变量中。我想将row 发送给一个名为pushData 的动作创建者,它接受row 作为输入。我的代码如下所示。

function onAfterSaveCell(row, cellName, cellValue){
  this.props.pushData(row);
} 

const cellEditProp = {
  mode: "click",
  blurToSave: true,
  afterSaveCell: onAfterSaveCell
};

class Feature extends Component {
  componentWillMount() {
    this.props.fetchMessage();
  }

  render() {
    if (!this.props.message) return null

    return (
    <div>
      <BootstrapTable
              data={this.props.message}
              cellEdit={cellEditProp}
              >
        <TableHeaderColumn dataField="ccyCode" isKey={true} dataSort={true}>Valutakod</TableHeaderColumn>......

当我运行代码时出现错误Uncaught TypeError: Cannot read property 'props' of undefined。我认为这是因为propsclass Feature 之外不可用。我尝试将onAfterSaveCell 函数和cellEditProp 移入class Feature,但这给了我一个编译错误。我怎样才能使propsclass Feature 之外可以访问,或者应该以其他方式解决这个问题?

【问题讨论】:

    标签: javascript reactjs react-redux react-bootstrap-table


    【解决方案1】:

    你是对的,你不能在课堂外使用this关键字。所以显而易见的答案是在类中定义你的回调函数。我认为您出现编译错误的原因是由于语法错误,因为这应该可以正常工作:

    class Feature extends Component {
      constructor(props, context) {
        super(props, context);
        this.onAfterSaveCell = this.onAfterSaveCell.bind(this); // important!
      }
    
      componentWillMount() {
        this.props.fetchMessage();
      }
    
      onAfterSaveCell(row, cellName, cellValue) {
        this.props.pushData(row);
      }
    
    
    
      render() {
        if (!this.props.message) return null
    
        return (
        <div>
          <BootstrapTable
                  data={this.props.message}
                  cellEdit={{
                    mode: "click",
                    blurToSave: true,
                    afterSaveCell: this.onAfterSaveCell
                    }}
                  >
            <TableHeaderColumn dataField="ccyCode" isKey={true} dataSort={true}>Valutakod</TableHeaderColumn>......
    

    【讨论】:

      猜你喜欢
      • 2019-12-21
      • 2021-04-09
      • 1970-01-01
      • 2021-04-12
      • 2020-05-04
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多