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

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

如何將父組件狀態數據以變量的形式傳遞給子組件

如何將父組件狀態數據以變量的形式傳遞給子組件

慕容708150 2021-10-21 10:27:05
我有一個父組件(index.js),它有一個狀態x:[],狀態包含數據[{…}, {…}, {…}]&我有一個子組件(child.jsx),在子組件(child.jsx)中,我想將父組件數據保存[{…}, {…}, {…}]在一個變量中在子組件中。父組件(index.js)//here i have more importsimport Child from "./child"export default class Index extends Component {    constructor(props) {        super(props);        this.state = {              x: [],          };    }//some functionsrender() {    const { x } = this.state;    console.log(x, "this is the data")        // x contains data [{…}, {…}, {…}]          return (           <div className="class">                                                             <Autocomplete x={this.state.x} />               </div>            }}子組件(child.jsx)//here i have importsconst suggestions =  here i want x data from the parent component;//some functionsexport default function Child(props) { return (    <div className="material">      <div className={classes.root}           <Autosuggest          {...props.x}        />      </div>    </div>  );}當我嘗試傳遞一些道具時,主要是出現未定義的錯誤。預期結果:"x data from the parent component" const suggestions = [{…}, {…}, {…}];
查看完整描述

3 回答

?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

您無法訪問其范圍之外的任何組件的 props,因此發送到 child 的 props 只能在子組件內部訪問,而不是在所有文件中,因為同一文件中可能有多個子組件。


Either use let like this: 



    let suggestions;

    //some functions


    export default function Child(props) {

    suggestions = props.x;

     return (

        <div className="material">

          <div className={classes.root}   

            <Autosuggest

              {...props.x}

            />

          </div>

        </div>

      );


    }



Or



export default function Child(props) {


const suggestions = props.x;

 return (

    <div className="material">

      <div className={classes.root}   

        <Autosuggest

          {...props.x}

        />

      </div>

    </div>

  );


}


查看完整回答
反對 回復 2021-10-21
?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

您將建議置于功能組件的范圍之外,因此您無法訪問 props。

您需要在 Child 中移動建議:


export default function Child(props) {


const suggestions =  props.x;


 return (

    <div className="material">

      <div className={classes.root}   

        <Autosuggest

          {...props.x}

        />

      </div>

    </div>

  );


}

我假設你從父組件渲染子組件,并給了他道具 x。


查看完整回答
反對 回復 2021-10-21
?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

您應該將數據(道具)從父組件傳遞給當前組件,然后再次將其傳遞給子組件,或者您可以簡單地使用上下文系統 閱讀上下文

Context 旨在共享可被視為“全局”的 React 組件樹的數據

我希望你得到這個想法并為你工作


查看完整回答
反對 回復 2021-10-21
  • 3 回答
  • 0 關注
  • 195 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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