Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在父组件和子组件之间传递数据_Javascript_Reactjs - Fatal编程技术网

Javascript 如何在父组件和子组件之间传递数据

Javascript 如何在父组件和子组件之间传递数据,javascript,reactjs,Javascript,Reactjs,我正在学习通过教程在父组件和子组件之间传递数据。我仔细检查了我的代码,仍然没有找出错误 myindex.js import React, {Component} from 'react'; import ReactDom from 'react-dom'; import {Header} from './components/Header'; import {Home} from './components/Home'; class App extends Component { cons

我正在学习通过教程在父组件和子组件之间传递数据。我仔细检查了我的代码,仍然没有找出错误

myindex.js

import React, {Component} from 'react';
import ReactDom from 'react-dom';
import {Header} from './components/Header';
import {Home} from './components/Home';

class App extends Component {
  constructor(){
    super();
    this.state ={
      HomeLink:"home"
    };
  }
  onGreet(){
    alert("hello");
  }

  onChangeLinkName(newName){
    this.setState({
      HomeLink:newName
    });
  }
  render(){
    return (
      <div className="container">
        <div className="row">
          <div className="col-xs-10 col-xs-offset-1">
            <Header HomeLink={this.state.HomeLink} />
          </div>
        </div>
        <div className="row">
          <div className="col-xs-10 col-xs-offset-1">
            <Home
            name={"max"}
             initialAge={27}
             greet={this.onGreet}>
             changeLink={this.onChangeLinkName.bind(this)}
              <p>This is a paragraph passed from props</p>
            </Home>
          </div>
        </div>
      </div>
    );
  }
}
ReactDom.render(
  <App/>, window.document.getElementById("root")
);

将要传递的道具切换到:

changeLink={this.onChangeLinkName}

在父级的构造函数中:

this.onChangeLinkName=this.onChangeLinkName.bind(this)

最后,在按钮调用中:


更改链接

代码中有一个输入错误

<Home
  name={"max"}
  initialAge={27}
  greet={this.onGreet}>
  changeLink={this.onChangeLinkName.bind(this)}
    <p>This is a paragraph passed from props</p>            
</Home>

changeLink={this.onChangeLinkName.bind(this)}
这是一段从道具传来的段落

请注意,在使用以下字符设置属性
greet
之后,您是如何关闭
Home
组件的:
。您想在将
changeLink
设置为道具后关闭它,以便将
向下移动到
this.onChangeLinkName.bind(this)}

这将修复您的错误,您应该能够继续前进

Uncaught TypeError: this.props.changeLink is not a function
<Home
  name={"max"}
  initialAge={27}
  greet={this.onGreet}>
  changeLink={this.onChangeLinkName.bind(this)}
    <p>This is a paragraph passed from props</p>            
</Home>