【问题标题】:passing function in React JsReact Js 中的传递函数
【发布时间】:2021-02-23 21:03:51
【问题描述】:

我需要将bookLeacture 函数从AvailableCourses 传递到LectureItem(在按钮onClick 内)。但我想我只能在LectureItem 中定义变量,但不能定义为函数。您能解释一下如何调用和定义它吗?

const LectureItem = props => {
  let l = props.lecture;
  // let bookLeacture=props.bookLeacture
  return (
    <>
      <Container>
        <Row>
          <Col>
            <Alert variant="primary">
              <Row>
                {l.booked === false && (
                  <Col>
                    <Button
                      onClick={this.bookLeacture(l.lectureId)}
                      variant="success"
                      block
                    >
                      Book Now
                    </Button>
                  </Col>
                )}
              </Row>
            </Alert>
          </Col>
        </Row>
      </Container>
    </>
  );
};

class AvailableCourses extends React.Component {
  bookLeacture = id => {
    API.bookLeacture(id)
      .then(res => {
        console.log(res);
        this.setState({ lectures: res, loading: null, serverErr: null });
      })
      .catch(err => {
        this.setState({ serverErr: true, loading: null });
      });
  };

  constructor(props) {
    super(props);
    this.state = { lectures: [] };
  }
  render() {
    return (
      <>
        <Container fluid>
          <Row className="justify-content-md-center below-nav">
            <h3>Available Courses: </h3>
          </Row>
          {this.state.lectures.map(e => {
            return <LectureItem lecture={e} bookLeacture={this.bookLeacture} />;
          })}
        </Container>
      </>
    );
  }
}
export default AvailableCourses;

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

那里有一个功能组件,它没有分类参数。这意味着,this 在此处无效。因此,您需要做的就是更改以下内容:

onClick={this.bookLeacture(l.lectureId)}

对此,加上上面的方法也不是正确的,它会立即执行:

onClick={() => bookLeacture(l.lectureId)}

此外,您不需要片段 &lt;&gt;&lt;/&gt; 来返回 Container


最终我会做这样的事情:

const LectureItem = ({ lecture, bookLeacture }) => {
  return (
    <Container>
      <Row>
        <Col>
          <Alert variant="primary">
            <Row>
              {lecture.booked === false && (
                <Col>
                  <Button
                    onClick={() => bookLeacture(lecture.lectureId)}
                    variant="success"
                    block
                  >
                    Book Now
                  </Button>
                </Col>
              )}
            </Row>
          </Alert>
        </Col>
      </Row>
    </Container>
  );
};

class AvailableCourses extends React.Component {
  state = { lectures: [] };
  bookLeacture = id => {
    API.bookLeacture(id)
      .then(res => {
        console.log(res);
        this.setState({ lectures: res, loading: null, serverErr: null });
      })
      .catch(err => {
        this.setState({ serverErr: true, loading: null });
      });
  };
  render() {
    return (
      <Container fluid>
        <Row className="justify-content-md-center below-nav">
          <h3>Available Courses:</h3>
        </Row>
        {this.state.lectures.map(e => {
          return <LectureItem lecture={e} bookLeacture={this.bookLeacture} />;
        })}
      </Container>
    );
  }
}
export default AvailableCourses;

我还会做一些额外的事情:

  1. 使用MyAlert 组件使警报看起来更整洁。
  2. 添加一个key 属性使其正常工作。
  3. 删除不必要的片段&lt;&gt;&lt;/&gt;
  4. 删除旧的构造函数概念并添加状态。

完全优化的来源:

const MyAlert = ({ children }) => (
  <Container>
    <Row>
      <Col>
        <Alert variant="primary">
          <Row>{children}</Row>
        </Alert>
      </Col>
    </Row>
  </Container>
);

const LectureItem = ({ lecture, bookLeacture }) => {
  return (
    <MyAlert>
      {lecture.booked === false && (
        <Col>
          <Button
            onClick={() => bookLeacture(lecture.lectureId)}
            variant="success"
            block
          >
            Book Now
          </Button>
        </Col>
      )}
    </MyAlert>
  );
};

class AvailableCourses extends React.Component {
  state = { lectures: [] };
  bookLeacture = id => {
    API.bookLeacture(id)
      .then(res => {
        console.log(res);
        this.setState({ lectures: res, loading: null, serverErr: null });
      })
      .catch(err => {
        this.setState({ serverErr: true, loading: null });
      });
  };
  render() {
    return (
      <Container fluid>
        <Row className="justify-content-md-center below-nav">
          <h3>Available Courses:</h3>
        </Row>
        {this.state.lectures.map((e, key) => {
          return (
            <LectureItem
              lecture={e}
              bookLeacture={this.bookLeacture}
              key={key}
            />
          );
        })}
      </Container>
    );
  }
}
export default AvailableCourses;

【讨论】:

    【解决方案2】:

    你已经走上正轨了。

    你必须在按钮上做这样的事情。

    但我认为您也希望传递项目的“id”,所以请执行以下操作。

    【讨论】:

    • 但它不是类组件,this 无效对吧?
    • 是的,这不是类组件,所有这些代码都在一个文件中
    • 是的!我没看到。您的解决方案适用于这种情况。
    猜你喜欢
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2016-03-23
    相关资源
    最近更新 更多