子JSX.Elementsを1つ以上受け入れ、余分なコールバックをReact.cloneElement(child, { onCancel:() => {} }
でレンダリングするときに渡すコンポーネントがあると仮定します。子要素をクローンしてTypeScriptで余分な小道具を追加するReactコンポーネントを入力する
質問(抜粋)におけるコンポーネント:アクションに質問(抜粋)で
interface XComponentProps {
onCancel: (index: number) => void;
}
class XComponent extends React.Component<XComponentProps> {
render() {
const { onCancel } = this.props;
const children = typeof this.props.children === 'function' ?
React.cloneElement(this.props.children, { onCancel:() => onCancel() }) :
this.props.children.map((child, idx) => (
React.cloneElement(child, { onCancel:() => onCancel(idx) })
));
return <div>{children}</div>;
}
}
コンポーネント:
interface UserComponentProps { caption: string }
const UserComponent = (props: UserComponentProps) => (
<button onClick={props.onClose}>{props.caption || "close"}</button>
);
ReactDOM.render(
<XComponent onCancel={handleCancel}>
<UserComponent />
<UserComponent />
<UserComponent />
</XComponent>
);
今TSCはUserComponent
がでonCancel
を持っていないことを不平を言っていますその小道具のインターフェース定義は、実際にはそうではありません。 1つの最も簡単な修正は、onCancel
からUserComponentProps
までのインターフェイスを手動で定義することです。
しかし、子ノードの小道具定義を変更しないで修正して、コンポーネントが任意のReact要素を受け入れることができるようにしたい。このようなシナリオでは、XComponent
(親)レベルで渡された暗黙的な小道具を持つ戻り要素の型を定義する方法はありますか?これは、独自の特性に加えてUserComponentPropsにXComponentPropsのすべてのプロパティを与える
interface UserComponentProps extends XComponentProps { caption: string }
:あなたはインターフェイスの継承を使用することができます
感謝を変更することなく、それを達成したいです! TSCが親と子の間の関係を知ることができるように、関数として渡すのが理にかなっています。 – shuntksh