javascript - 有没有一种方法可以在没有 onClick 的情况下将道具从孩子传递给父母
问题描述
我已经看到了一些示例,这些示例显示了如何使用子组件上的 onClick on onChange 事件将道具从子组件传递给其父组件,但我正在努力弄清楚如何被动地传递道具。
我想要的是让子组件执行获取操作,然后将响应传递给父组件。
// PARENT component
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
homeLink: 'inital'
}
}
handleNamechange(newName) {
this.setState({
homeLink: newName
})
}
render() {
return(
<section>
<h1>{this.state.homeLink}</h1>
<GetUserComponent
changeLink={this.handleNamechange.bind(this)}
/>
</section>
)
}
}
export default App;
我努力的部分是在没有 onClick 的情况下将道具发送给父级,并在获取完成后传递道具
// CHILD Component
class GetUserComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
homeLink: 'xxxx'
}
}
componentDidMount() {
fetch('https://someapi/getusername', {
})
.then(function(response) {
return response.json()
})
.then((data) => {
this.setState(
{ username: data }
)
})
}
onChangeLink() {
this.props.changeLink(this.state.homeLink)
}
render() {
return (
<div>
<span onClick={this.onChangeLink.bind(this)}
>Change Header Link</span>
</div>
)
}
}
export default GetUserComponent;
我不确定我是否做错了,或者这是否根本无法完成并且您必须使用点击事件,但无论哪种方式都非常感谢您的帮助。
解决方案
你必须调用父母函数:
componentDidMount() {
fetch('https://someapi/getusername', {
})
.then(function(response) {
return response.json()
})
.then((data) => {
this.props.changeLink(data);
})
}
然后它将执行该handleNamechange
函数并更新父状态。
推荐阅读
- java - java中的方阵和二次对角线
- c# - C#文件删除和释放过程需要很长时间
- rest - 'self' 的 REST API 过滤器
- express - 在 express 中替代模板引擎
- java - 需要在没有秒的情况下比较日期对象
- python - 如何停止在张量流网络上使用权重?
- c++ - C++ char数组特性:为什么字符串在数组末尾之前停止?
- python - Python Tkinter mainloop 增加了多线程应用程序中的处理时间
- java - Mapstruct 在使用 ObjectFactory 时无法映射属性
- google-bigquery - 如何在 BigQuery 中取消嵌套多个数组?