gpt4 book ai didi

javascript - 如何将参数从子函数传递给父reactjs

转载 作者:行者123 更新时间:2023-12-03 02:15:41 24 4
gpt4 key购买 nike

我创建了一个简单的应用程序组件,它呈现侧边栏和仪表板。在侧边栏中单击链接时,我想要执行 AJAX 请求并更改仪表板的状态。我已将单击处理程序函数移至 index.js 应用程序组件,以便它可以将 props 传递到仪表板。

index.js:

import React from "react";

import { NavBar } from "./components/NavBar";
import { NavBarSide} from "./components/NavBarSide";
import { Dashboard} from "./components/Dashboard"

import { render } from "react-dom";

class App extends React.Component {

handleNavClick(url) {
console.log(url)
}

render() {
return (
<div>
<NavBar/>
<div className="container-fluid">
<div className="row">
<Dashboard/>
<NavBarSide clickHandler={(url) => this.handleNavClick(url)}/>
</div>
</div>
</div>
)
}
}


render(<App/>, window.document.getElementById("root"));

我的 NavBarSide 就像这样......

NavBarSide.js:

import React from 'react';
import { Nav, NavItem, NavLink } from 'reactstrap';

export class NavBarSide extends React.Component {
render() {
return (
<Nav className="col-md-2 d-none d-md-block bg-light sidebar">
<div className="sidebar-sticky">
<ul className="nav flex-column">
<NavItem className="nav-item">
<NavLink className="nav-link" href="#" onClick={this.props.clickHandler("/api/highest/price")}>Highest Price</NavLink>
</NavItem>
</ul>
</div>
</Nav>
);
}
}

该函数似乎立即执行,而不是预期的行为。

如果有更好的方法来做到这一点(我认为使用react-router v4),如果它也包含在内将会很有帮助。

最佳答案

export default class NavBarSide extends React.Component {
constructor(props) {
super(props);

// Bind the function only once - on creation
this.onClick = this.onClick.bind(this);
}

onClick() {
this.props.clickHandler("/api/highest/price");
}

render() {
return (
<Nav className="col-md-2 d-none d-md-block bg-light sidebar">
<div className="sidebar-sticky">
<ul className="nav flex-column">
<NavItem className="nav-item">
<NavLink className="nav-link" href="#" onClick={this.onClick}>Highest Price</NavLink>
</NavItem>
</ul>
</div>
</Nav>
);
}
}

关于javascript - 如何将参数从子函数传递给父reactjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49372858/

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