首页 > 解决方案 > 如何在 React 中执行函数?

问题描述

我是 React 的初学者,请有人帮忙,我写了这个函数:

import React, {
Component }
from 'react';
import './Grid.css';
import test from "../product.json";
import $ from 'jquery';


class Grid extends Component {

makeGrid = () =>{

    var data = test.map( x => [ x.name, x.price, ] );

    $( document ).ready(function() {
    console.log( "ready!" );
    $('.boxes').append('<div className = "boxi"> Success </div>')

    });

我想执行这个功能,所以我尝试了:

render() {


    return (
        <div className = "Grid" >
        < section className = "boxes" >

        < /section> < /div > );

        <h2> {this.makeGrid}</h2>

 }
}

export default Grid;

但即使console.log 不起作用也没有任何反应。请有人帮助我。

标签: javascriptjqueryhtmlreactjs

解决方案


给你一个解决方案

import React, { Component } from 'react';
import './Grid.css';
import test from "../product.json";
import $ from 'jquery';


class Grid extends Component {

  constructor(props) {
    this.makeGrid = this.makeGrid.bind(this);
  }
 
  makeGrid = () => {
    var data = test.map( x => [ x.name, x.price, ] );
    console.log( "ready!" );
    $('.boxes').append('<div className = "boxi"> Success </div>')
  }

  render() {
    return (
      <div className="Grid">
        <section className="boxes">
        </section> 
      < /div >
      <h2>
        {this.makeGrid()}
      </h2>
  );     
 }
}

export default Grid;

您需要绑定this到 makeGrid 方法。


推荐阅读