簡體   English   中英

將 prop 從父級傳遞給子級時出錯 - 類型無效

[英]Error while passing prop from parent to child - type is invalid

我知道這個網站上有很多類似的問題,但沒有一個與我的代碼匹配,所以我無法理解它們,因為我對 React JS 完全陌生。 基本上我正在制作一個骰子應用程序。 我分別為邊數和骰子數創建了一個類,我試圖將兩個類的邊數和骰子數傳遞到另一個類中,在那里我將計算可能的最大分數 -> 骰子數 * 邊數. 當我將邊數傳遞給子類時,它是成功的,但是當我傳遞骰子數時,它給了我錯誤:

React.createElement:類型無效——需要一個字符串或一個類/函數,但得到:未定義

編輯:終於明白了。 它與類本身無關,我在子類之前渲染了 NoOfDice 類

Child 期望 noOfDice 作為道具,這就是為什么它在一種情況下起作用而不在另一種情況下起作用。 您應該保持相同的名稱。 我已將您的代碼與 prop 名稱編輯為acceptedNumber 還要檢查子組件是否已正確導入。

嘗試這個:

// NoOfSides
class NoOfSides extends React.Component {
  constructor(props) {
    super(props);
    this.state = { mystate: 6 };
  }
  render() {
    return (<div>
      <h1>Number of Sides</h1>
      <h2 >
        {this.state.mystate}
      </h2>
      <Child acceptedNumber={this.state.mystate} />
    </div>
    );
  }
};
// NoOfDice
class NoOfDice extends React.Component {
  constructor(props) {
    super(props);
    this.state = { mystate: 1 };
  }

  render() {
    return (<div>
      <h1>Number of Dice</h1>
      <h2 >
        {this.state.mystate}
      </h2>
      <Child acceptedNumber={this.state.mystate} />
    </div>
    );
  }
};
// Child
class Child extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>{this.props.acceptedNumber}</h1>
      </div>
    )
  }
}

您發布的代碼沒有問題,如下所示

 class Child extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h1>{this.props.noOfSides}</h1> <h1>{this.props.noOfDice}</h1> </div> ); } } class NoOfDice extends React.Component { constructor(props) { super(props); this.state = { mystate: 1 }; } render() { return ( <div> <h1>Number of Dice</h1> <h2>{this.state.mystate}</h2> <Child noOfDice={this.state.mystate} /> //error is in this line </div> ); } } ReactDOM.render(<NoOfDice />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM