2017-02-15 8 views
7

मैं प्रतिक्रिया और प्रकारलेख का उपयोग कर रहा हूं। मेरे पास एक प्रतिक्रिया घटक है जो एक रैपर के रूप में कार्य करता है, और मैं अपनी संपत्तियों को अपने बच्चों को कॉपी करना चाहता हूं। मैं क्लोन तत्व का उपयोग करने के लिए प्रतिक्रिया की मार्गदर्शिका का पालन कर रहा हूं: https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement। लेकिन जब React.cloneElement मैं टाइपप्रति से निम्न त्रुटि मिल का उपयोग कर का उपयोग करते हुए:बच्चों को गुण देते समय React.cloneElement को सही टाइपिंग कैसे असाइन करें?

Argument of type 'ReactChild' is not assignable to parameter of type 'ReactElement<any>'.at line 27 col 39 
    Type 'string' is not assignable to type 'ReactElement<any>'. 

मैं कैसे सही टाइपिंग के react.cloneElement को असाइन कर सकते?

यहाँ एक उदाहरण है कि उपरोक्त त्रुटि प्रतिकृति है:

import * as React from 'react'; 

interface AnimationProperties { 
    width: number; 
    height: number; 
} 

/** 
* the svg html element which serves as a wrapper for the entire animation 
*/ 
export class Animation extends React.Component<AnimationProperties, undefined>{ 

    /** 
    * render all children with properties from parent 
    * 
    * @return {React.ReactNode} react children 
    */ 
    renderChildren(): React.ReactNode { 
     return React.Children.map(this.props.children, (child) => { 
      return React.cloneElement(child, { // <-- line that is causing error 
       width: this.props.width, 
       height: this.props.height 
      }); 
     }); 
    } 

    /** 
    * render method for react component 
    */ 
    render() { 
     return React.createElement('svg', { 
      width: this.props.width, 
      height: this.props.height 
     }, this.renderChildren()); 
    } 
} 

उत्तर

12
समस्या

कि definition for ReactChild इस है:

type ReactText = string | number; 
type ReactChild = ReactElement<any> | ReactText; 

आप यह सुनिश्चित करें कि child हमेशा एक ReactElement तो है कर रहे हैं इसे कास्ट करें:

return React.cloneElement(child as ReactElement<any>, { 
    width: this.props.width, 
    height: this.props.height 
}); 

अन्यथा का उपयोग isValidElement type guard:

if (React.isValidElement(child)) { 
    return React.cloneElement(child, { 
     width: this.props.width, 
     height: this.props.height 
    }); 
} 

(मैं इसे पहले उपयोग नहीं किया है, लेकिन परिभाषा फ़ाइल यह वहाँ के अनुसार)

संबंधित मुद्दे