2016-09-12 164 views
0

使用React.createClass({})我可以輕鬆地將道具傳遞給子組件。如何處理React.Component{}警告未知支柱

export default class Parent extends React.Component { 
    // imported Child and in the render: 
    render(){ 
    return <Child name={this.state.foo} /> 
    } 
} 

export default class Child extends React.Component { 
} 

警告未知道具「名」

回答

1

傳遞prop的方式是一樣的,但是你需要檢查你是否正確定義狀態變量。看下面的實現。上述錯誤可能有一組原因:

您使用{... this.props}還是cloneElement(element,this.props)? 您的組件正在將其自己的道具直接轉移給孩子 元素(例如, https://facebook.github.io/react/docs/transferring-props.html)。當 將道具轉移到子組件時,您應確保您 不會意外轉發旨在由父組件解釋的 道具。

您在本地DOM節點上使用非標準DOM屬性, 可能表示自定義數據。如果您嘗試將自定義 數據附加到標準DOM元素,請考慮使用MDN中描述的自定義數據屬性 。

React尚未識別您指定的屬性。這可能會在未來版本的React中修復,其中 可能會被修復。但是,React目前的 會去除所有未知屬性,因此在您的React應用程序 中指定它們不會導致它們被渲染。

還要檢查您使用的是哪個版本的反應,以及您是否正確設置了反應以使用ES6語法。

PS:我使用的版本0.14.8用於以下代碼段

class Parent extends React.Component { 
 
    // imported Parent and in the render: 
 
    constructor(){ 
 
    super(); 
 
    this.state = { 
 
     foo: 'Hello World' 
 
    } 
 
    } 
 
    render(){ 
 
    return <Child name={this.state.foo} /> 
 
    } 
 
} 
 

 
class Child extends React.Component { 
 
    
 
    render() { 
 
    return (
 
     <div>{this.props.name}</div> 
 
    ) 
 
    } 
 
} 
 

 

 
ReactDOM.render(<Parent />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script> 
 
<div id="container"></div>