자체 메서드로 호출 할 수 있도록 자체적으로 구성 요소에 액세스하려고하는데 성공하지 못했습니다.Typescript에 반응하여 주 구성 요소에서 하위 구성 요소의 메서드를 호출하는 방법?
TestComponent
은 print()
이라는 간단한 방법이 있습니다. 그 print()
메서드를 MainComponent
에서 호출하고 싶습니다.
class TestComponent extends React.Component<IProps, IState) {
print() {
console.log('From TestComponent');
}
render() {
return <h1>Item</h1>;
}
}
class MainComponent extends React.Component<IProps, IState) {
private list:Array<TestComponent>; //This is going to throw an error in Typescript. It expects type of JSX Element.
render() {
for(let i=0; i<5; i++) list.push(<TestComponent/>); //<TestComponent> is recognised as a JSX element instead so this will throw an error
list.forEach((component) => component.print()); //Since this is JSX Element, calling print() will throw unknown function print() error.
return <h1>Main Component</h1>{list};
}
}
그것은 내가 타이프에서 개체 유형으로 TestComponent
을 사용할 수 없다는 것을 밝혀 : 그래서 이런 일을했다. 내 list
배열의 형식을 JSX.Element
으로 설정해야 작동합니다. 그러나 그렇게한다면 TestComponent
의 print()
메서드를 MainComponent
에서 호출하도록 형식을 "상향 캐스트"할 수 없습니다.
하위 구성 요소가 포함 된 주 구성 요소에서 하위 구성 요소의 메서드를 호출하려면 어떻게해야합니까?
Typescript에서 구성 요소 유형을 어떻게 정의해야합니까?