2017-08-31 28 views
0

我已閱讀PropTypes的the official documentationthe npm package description爲什麼React沒有檢查我的propTypes?

然而,當我運行此代碼,

const propTypes = { 
    foo: PropTypes.string.isRequired, 
    bar: PropTypes.number.isRequired, 
    umu: PropTypes.string 
}; 

const defaultProps = { 
    umu: "default value" 
}; 

class MyComp extends React.Component { 
    constructor(props){ 
     super(props); 
    } 

    render() { 
     return (
     <ul> 
      <li>foo is {this.props.foo}</li> 
      <li>bar is {this.props.bar}</li> 
      <li>umu is {this.props.umu}</li> 
     </ul> 
     ); 
    } 
} 
MyComp.propTypes = propTypes; 
MyComp.defaultProps = defaultProps; 

class MyWrapper extends React.Component{ 
    render() { 
     return (
      <div> 
       <MyComp bar="string and not a number"/> 
      </div> 
     ); 
    } 
} 

ReactDOM.render(React.createElement(MyWrapper, null, null), document.getElementById("app")); 

propTypes不檢查,但所需的屬性foo沒有設置和屬性bar不是一個數字。有人可以告訴我我做錯了什麼嗎? 下面是相應的CodePen

非常感謝。

回答

1

即使驗證失敗,該組件也會呈現,這更多的是對開發人員的警告,因此您會在控制檯上看到錯誤。 CodePen不會顯示這些警告,但是,也許是因爲您正在使用生產版本的反應?無論哪種方式,這都是正確的行爲。

+0

兩個問題: 1.我該如何選擇CodePen中的反應開發版本?我是React和CodePen的新手,只是從筆設置中的「快速添加」中選取了React。 2.我在Visual Studio代碼中使用我的'create-react-app'項目獲得相同的行爲。根本沒有警告。無論如何他們應該出現在哪裏?在建築物的終端輸出?你有沒有更進一步的提示? – Joerg

+1

我不確定CodePen,但不是,警告會在您的瀏覽器控制檯的運行時顯示。只需運行您的應用程序並觀察瀏覽器中的那些控制檯錯誤 – ZekeDroid

相關問題