如何处理组件中的onClick方法?

时间:2019-03-21 15:10:52

标签: reactjs

我相信我的道具设置正确,但是我不断收到“无法读取未定义的属性'props'”

子组件:

 const SearchResults = props => (
     <div>
    <div className="row" ><h4 style={{margin:"auto", marginBottom:"15px"}}>Search Results:</h4></div>
      <table className="table table-striped">
       <thead>
         <tr>
          {props.labels.map(label => ( <th key={label.Id}>{label.DisplayName}</th>))}
         </tr>
       </thead>
      <tbody>
{ props.contracts.map((contract, i) => <tr key={i} data-id={contract.Id}  onClick={() => this.props.handleContract(contract.Fields.filter(field => field.DataField==="IDXT001").map(field => field.DataValue))} className="clickable-row">{contract.Fields.map( docs =>  <td key={docs.Id}><span id={docs.DataField}>{docs.DataValue}</span></td>)}</tr> )}
      </tbody>
    </table>
    </div>
   )

父母:

class SearchPage extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        labels: [],
        contracts: [],
        formValues:"",
        pdfs:[],
        id:"",
      };
    }
<SearchResults 
    labels={this.state.labels}
    contracts={this.state.contracts} 
    pdfs={this.state.pdfs}
    handleContract={this.onClick}
/>

1 个答案:

答案 0 :(得分:5)

您需要将this.props.handleContract更改为props.handleContractthis在您的功能组件中不存在。

 const SearchResults = props => (
  <div>
    <div className="row" ><h4 style={{ margin: "auto", marginBottom: "15px" }}>Search Results:</h4></div>
    <table className="table table-striped">
      <thead>
        <tr>
          {props.labels.map(label => (<th key={label.Id}>{label.DisplayName}</th>))}
        </tr>
      </thead>
      <tbody>
        {props.contracts.map((contract, i) => <tr key={i} data-id={contract.Id} onClick={() => props.handleContract(contract.Fields.filter(field => field.DataField === "IDXT001").map(field => field.DataValue))} className="clickable-row">{contract.Fields.map(docs => <td key={docs.Id}><span id={docs.DataField}>{docs.DataValue}</span></td>)}</tr>)}
      </tbody>
    </table>
  </div>
);

在您的父母身上,确保您已绑定注释中提到的onClick函数。

class SearchPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      labels: [],
      contracts: [],
      formValues: "",
      pdfs: [],
      id: ""
    };
  }

  onClick = () => {
    // Bind the function like this.
  }

  render() {
    return (
      <SearchResults
        labels={this.state.labels}
        contracts={this.state.contracts}
        pdfs={this.state.pdfs}
        handleContract={this.onClick}
      />
    );
  }
}