gpt4 book ai didi

javascript - 如何在父子组件之间传递数据

转载 作者:行者123 更新时间:2023-12-03 03:57:37 25 4
gpt4 key购买 nike

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

我的index.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")
);

Home.js

按钮更改链接 onClick 事件正在调用changeLink 函数,该函数将 newlink 传递给 props。

import React from 'react';

export class Home extends React.Component {
constructor(props){
super();
this.state = {
age:props.initialAge,
status:0,
homeLink:"changed link"
};
setTimeout(() => {
this.setState({
status:1
});
},3000);
}
onMakeOlder(){
this.setState({
age:this.state.age+3
});
}
onChangeLink(){
this.props.changeLink(this.state.homeLink);
}

render(){
return(
<div>
<p>In a new Component</p>
<p>Your name is {this.props.name} and your age is {this.state.age}</p>
<p>{this.state.status}</p>
<hr/>
<button onClick={()=> this.onMakeOlder()}>make me older</button>
<hr/>
<button onClick={this.props.greet}>greet</button>
<hr/>
<button onClick={this.onChangeLink.bind(this)}>change link</button>
</div>
);
}
}

Home.propTypes = {
name:React.PropTypes.string,
age:React.PropTypes.number,
user:React.PropTypes.object,
children: React.PropTypes.element.isRequired,
greet:React.PropTypes.func,
changeLink:React.PropTypes.func
};

错误:-

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>

请注意,在使用以下字符设置属性 greet 后,如何立即关闭 Home 组件:>。您想在将 changeLink 设置为 prop 后关闭它,因此将 > 向下移动到 this.onChangeLinkName.bind(this)}

这将解决您的错误,您应该能够继续前进。

关于javascript - 如何在父子组件之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44867214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com