gpt4 book ai didi

javascript - 在 React 中传递状态更新器 clickHandler

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

我有一个 React 应用程序,例如:

Main.js-

import React, { Component } from 'react';
import _ from 'underscore';

import ApplicationsButtons from '../components/ApplicationsButtons';


let applications_url = 'http://127.0.0.1:8889/api/applications'


export default class Main extends Component {

constructor(props) {
super(props);
this.state = {applications: [], selected_app: 1};
this.updateSelectedApp = this.updateSelectedApp.bind(this);
}

componentDidMount() {
let self = this;
$.ajax({
url: applications_url,
method: 'GET',
success: function(data) {
console.log(data);
let objects = data.objects;
let apps = objects.map(function(object) {
return {name: object.name, id: object.id};
});
console.log(apps);
self.setState({applications: apps});
}
});
}

updateSelectedApp(id) {
this.setState({selected_app: id});
}

render() {

return (
<div>
{this.state.selected_app}
<ApplicationsButtons apps={this.state.applications} />
</div>
);
}
}

ApplicationsButtons.js-

import React, { Component } from 'react';


export default class ApplicationsButtons extends Component {

render() {
var buttons = null;
let apps = this.props.apps;
let clickHandler = this.props.clickHandler;
if (apps.length > 0) {
buttons = apps.map(function(app) {
return (<button key={app.id}>{app.name} - {app.id}</button>);
// return (<button onClick={clickHandler.apply(null, app.id)} key={app.id}>{app.name} - {app.id}</button>);
});
}

return (
<div>
{buttons}
</div>
);
}
}

我想将 onClick 传递给将更改当前所选应用程序的按钮。不知何故,我刚刚在 React 中得到了第一个无限循环(“setState 刚刚运行了 20000 次”)。显然,当我尝试传递要在单击时调用的事件处理程序时,我告诉它继续调用它。

onClick 函数应该更改 state.selected_app对于Main组件,基于id对于被单击的按钮。

最佳答案

您没有将处理程序作为 Prop 传递。这是你应该做的:

render() {
return (
<div>
{this.state.selected_app}
<ApplicationsButtons
apps={this.state.applications}
handleClick={this.updateSelectedApp}
/>
</div>
);
}

在应用程序按钮中:

render() {
var buttons = null;
let apps = this.props.apps;
let clickHandler = this.props.handleClick;
if (apps.length > 0) {
buttons = apps.map(app =>
<button key={app.id} onClick={() => clickHandler(app.id)}>{app.name} - {app.id}</button>);
);
}

return (
<div>
{buttons}
</div>
);
}

关于javascript - 在 React 中传递状态更新器 clickHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335250/

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