reactjs - คอมโพเนนต์ลำดับสูง (HOC) ของ React ใน TypeScript
ฉันกำลังพยายามเขียน React HOC ใน TypeScript แต่ฉันไม่สามารถกำหนดชนิดได้ถูกต้อง ฉันไม่แน่ใจว่าสิ่งที่ฉันพยายามทำสามารถทำได้หรือไม่
นี่คือโค้ดของฉัน
import * as React from 'react'
export default function Ajax<Props, State>(InnerComponent: typeof React.Component): React.ComponentClass<Props & State> {
return class extends InnerComponent<Props & State,any> {
constructor() {
super()
this.state = {
request: 'initial'
}
}
changeRequest(newRequest) {
this.setState({request: 'loading'})
}
render() {
return <InnerComponent
{...this.props }
{...this.state}
changeRequest={this.changeRequest}
/>
}
}
}
ถ้าฉันแค่ส่ง props และ state ไปยัง child มันก็ทำงาน แต่ฉันจะเขียนคำจำกัดความอย่างไรเพื่อให้สามารถส่ง props เพิ่มเติมไปยัง component ที่ถูกห่อได้? ในกรณีนี้คือ prop changeRequest
ขอบคุณ
คำตอบ #1
ฉันสามารถทำให้มันทำงานได้ แต่ฉันไม่แน่ใจว่านี่เป็นวิธีที่ถูกต้องหรือไม่ แต่ตอนนี้คอมไพเลอร์ไม่แสดงข้อผิดพลาดและโค้ดทำงานได้ สำหรับที่คอมไพเลอร์หยุดแสดงข้อผิดพลาด ฉันต้องเพิ่ม props เป็นวัตถุของจาวาสคริปต์
นี่คือโค้ดที่ทำงานของฉัน:
import * as React from 'react'
export default function Ajax<Props, State> (InnerComponent: typeof React.Component): React.ComponentClass<Props & State> {
return class extends InnerComponent<Props & State, any> {
constructor() {
super()
this.state = {
request: 'initial'
}
this.changeRequest = this.changeRequest.bind(this)
}
changeRequest(newRequest) {
this.setState({request: 'loading'})
}
render() {
return <InnerComponent {...this.props} {...this.state} {...{onCLick: this.changeRequest}}/>
}
}
}
คำตอบ #2
ฉันเชื่อว่าคุณแค่ต้องผูกบริบทของ HOC กับฟังก์ชัน changeRequest
constructor() {
...
this.changeRequest = this.changeRequest.bind(this)
}
และตรวจสอบให้แน่ใจว่าคุณกำลังจัดการ prop ใน InnerComponent ตัวอย่างเช่น
<InnerComponent onClick={this.props.changeRequest}>
