猿问

如何将父组件状态数据以变量的形式传递给子组件

我有一个父组件(index.js),它有一个状态x:[],状态包含数据[{…}, {…}, {…}]&我有一个子组件(child.jsx),在子组件(child.jsx)中,我想将父组件数据保存[{…}, {…}, {…}]在一个变量中在子组件中。


父组件(index.js)


//here i have more imports

import Child from "./child"


export default class Index extends Component {

    constructor(props) {

        super(props);

        this.state = {  

            x: [],  

        };

    }


//some functions


render() {


    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 imports


const suggestions =  here i want x data from the parent component;


//some functions


export 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 = [{…}, {…}, {…}];


慕容708150
浏览 262回答 3
3回答

PIPIONE

您无法访问其范围之外的任何组件的 props,因此发送到 child 的 props 只能在子组件内部访问,而不是在所有文件中,因为同一文件中可能有多个子组件。Either use let like this:&nbsp;&nbsp; &nbsp; let suggestions;&nbsp; &nbsp; //some functions&nbsp; &nbsp; export default function Child(props) {&nbsp; &nbsp; suggestions = props.x;&nbsp; &nbsp; &nbsp;return (&nbsp; &nbsp; &nbsp; &nbsp; <div className="material">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className={classes.root}&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Autosuggest&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {...props.x}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }Orexport default function Child(props) {const suggestions = props.x;&nbsp;return (&nbsp; &nbsp; <div className="material">&nbsp; &nbsp; &nbsp; <div className={classes.root}&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <Autosuggest&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {...props.x}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; );}

侃侃尔雅

您将建议置于功能组件的范围之外,因此您无法访问 props。您需要在 Child 中移动建议:export default function Child(props) {const suggestions =&nbsp; props.x;&nbsp;return (&nbsp; &nbsp; <div className="material">&nbsp; &nbsp; &nbsp; <div className={classes.root}&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <Autosuggest&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {...props.x}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; );}我假设你从父组件渲染子组件,并给了他道具 x。

慕慕森

您应该将数据(道具)从父组件传递给当前组件,然后再次将其传递给子组件,或者您可以简单地使用上下文系统&nbsp;阅读上下文Context 旨在共享可被视为“全局”的 React 组件树的数据我希望你得到这个想法并为你工作
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答