【问题标题】:How to pass parent component state data to the child component in variable如何将父组件状态数据传递给变量中的子组件
【发布时间】:2019-09-18 07:16:29
【问题描述】:

我有一个父组件(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 = [{…}, {…}, {…}];

【问题讨论】:

  • 您在 Parent 中导入 Child 但从不对其执行任何操作,是否缺少某些代码?
  • 不是&lt;Autocomplete x={this.state.x} /&gt;,你的意思是&lt;Child x={this.state.x} /&gt;
  • 不,这是material.ui组件。

标签: javascript reactjs material-ui


【解决方案1】:

您将建议放在功能组件范围之外,因此您无法访问道具。
您需要将建议移入 Child:

export default function Child(props) {

const suggestions =  props.x;

 return (
    <div className="material">
      <div className={classes.root}   
        <Autosuggest
          {...props.x}
        />
      </div>
    </div>
  );

}

我假设你从 Parent 组件渲染 Child 组件,并给了他 prop x。

【讨论】:

  • 谢谢,当我尝试你的方法时让建议 = props.x; console.log(suggestions, "这是建议");那么建议是未定义的,没有得到数据。
  • 你从Index组件渲染子组件了吗?
【解决方案2】:

您不能访问其范围之外的任何组件的 props,因此发送给子组件的 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>
  );

}

【讨论】:

    【解决方案3】:

    您应该将数据(道具)从父组件传递给当前组件,然后再次将其传递给子组件,或者您可以简单地使用上下文系统 Read about context

    上下文旨在共享可被视为 React 组件树“全局”的数据

    我希望你明白这个想法并为你工作

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 2019-08-15
      • 1970-01-01
      • 2014-12-18
      • 2020-07-04
      • 2020-06-21
      • 2019-02-17
      • 2017-05-31
      • 1970-01-01
      相关资源
      最近更新 更多