亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

至尊寶的傳說 2022-06-05 16:53:27
我知道這個網站上有很多類似的問題,但沒有一個與我的代碼匹配,所以我無法理解它們,因為我對 React JS 完全陌生?;旧衔艺谧鲆粋€骰子應用程序。我已經分別為面數和骰子數量創建了一個類,我試圖將兩個類的面數和骰子數量傳遞到另一個類中,我將計算可能的最大分數 - >骰子數 * 面數. 當我將面數傳遞給子類時,它是成功的,但是當我傳遞骰子數時,它給了我錯誤:React.createElement:類型無效——期望一個字符串或一個類/函數,但得到:未定義編輯:終于明白了。它與類本身無關,我在子類之前渲染 NoOfDice 類
查看完整描述

2 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

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


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>


查看完整回答
反對 回復 2022-06-05
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

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>

    )

  }

}


查看完整回答
反對 回復 2022-06-05
  • 2 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號