【发布时间】: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;
【问题讨论】:
-
你已经返回了一个普通的组件,你为什么要把它包装在 Fragment 短代码中?该短代码用于如果您将返回不兼容的内容。
-
我在这里有一个类似问题的答案,How to set one component's state from another component in React。在这个问题中,我们在两个函数之间传递了
setState(),尽管可以使用任何函数。 -
欢迎来到 Stack Overflow。请看,What should I do when someone answers my question? 也可以通过tour 来熟悉如何使用这个平台。
标签: javascript reactjs